[英]How to sort an arraylist with different data type in java
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 :
所以我们会有:
Where numbers 5,8,4 represents price of each book.
其中数字 5、8、4 代表每本书的价格。 How can i sort this array descending by the price , and get the final output like this :
我怎样才能按价格降序对这个数组进行排序,并得到这样的最终输出:
Create an object Book to represent the name and price.创建一个对象 Book 来表示名称和价格。 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());
尝试这个 :-
Collections.sort(al, (ob1,ob2)-> -ob1.getPrice().compareTo(ob2.getPrice()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.