This question already has an answer here:
这个问题在这里已有答案:
- Sorting by property in Java 8 stream 1 answer
按Java 8流1属性排序
I have the following java class:
我有以下java类:
public class Customer {
private long id;
public long getId() {
return id;
}
}
And I also have a List<Customer> customers
. What is the most elegant way to sort the list by Customer.getId()
using a lambda expression?
我还有一个List
Right now I have this code:
现在我有这个代码:
Comparator<Customer> customerComparator = (previousCustomer, nextCustomer) ->
Long.compare(previousCustomer.getId(), nextCustomer.getId());
customers.sort(customerComparator);
But it feels clunky especially if I need to write a comparator for each different sort or for each different generic list. Could this be done with one line of code?
但是,如果我需要为每个不同的排序或每个不同的通用列表编写比较器,它会感到笨拙。这可以用一行代码完成吗?
3 个解决方案
#1
12
I think you may be looking for the Comparator.comparing...()
method:
我想你可能正在寻找Comparator.comparing ...()方法:
customers.sort(comparingLong(Customer::getId))
#2
10
In Java 8 you can write on one line.
在Java 8中,您可以在一行上书写。
customers.sort((a, b) -> Long.compare(a.getId(), b.getId());
If you make the Customer implements Comparable<Customer>
you can just do
如果您使Customer实现Comparable
customers.sort(Customer::compare);
or
customers.sort(null);
#3
4
Sort the List using Lambda Expression
使用Lambda表达式对列表进行排序
customers.sort((c1, c2) -> Long.compare(c1.getId(),c2.getId()));
#1
12
I think you may be looking for the Comparator.comparing...()
method:
我想你可能正在寻找Comparator.comparing ...()方法:
customers.sort(comparingLong(Customer::getId))
#2
10
In Java 8 you can write on one line.
在Java 8中,您可以在一行上书写。
customers.sort((a, b) -> Long.compare(a.getId(), b.getId());
If you make the Customer implements Comparable<Customer>
you can just do
如果您使Customer实现Comparable
customers.sort(Customer::compare);
or
customers.sort(null);
#3
4
Sort the List using Lambda Expression
使用Lambda表达式对列表进行排序
customers.sort((c1, c2) -> Long.compare(c1.getId(),c2.getId()));