Cristyan :
I have an arraylist which contains next data : name of an object and some details about him ( let's take as example a book and his price ). So we would have :
- Book_Nr1_Name 5
- Book_Nr2_Name 8
- Book_Nr3_Name 4
Where numbers 5,8,4 represents price of each book. How can i sort this array descending by the price , and get the final output like this :
- Book_Nr2_Name 8
- Book_Nr1_Name 5
- Book_Nr3_Name 4
Jason :
Create an object Book to represent the name and price. Then create a collection of all books. Then we sort by the price using a Comparator that compares Integer values. We then collect to a List since it's sorted.
static class Book {
private final String name;
private final int price;
Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
List<Book> books = Arrays.asList(
new Book("Book_Nr1_Name", 5),
new Book("Book_Nr2_Name", 8),
new Book("Book_Nr3_Name", 4));
List<Book> sortedByPrice = books.stream()
.sorted(Comparator.comparingInt(Book::getPrice).reversed())
.collect(Collectors.toList());
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=349043&siteId=1