For example, I want to have a class User
with attributes like this private int age, private String name
There are several objects
User user1 = new User(21,"张三") User user2 = new User(25,"李四") User user3 = new User(22,"王五") List<User> list = new ArrayList(); list.add(user1) add(user2) add(user3)
Now I want to sort them in ascending order of age, that is, the final display result of lisr is user1 user3 user2
How to write it using the lambda expression of java8?
This is a class similar to user. Comparing the count value inside can achieve the function, but why is the code in brackets gray?
Move the mouse up. ReportCan be replaced with Comparator.comparingInt more... (Ctrl F1)
The one upstairs is not friendly. The following method is more declarative, not the old imperative style
Isn’t it easier to read like this? Sort according to the
age
attribute ofUser
. If the attribute is int, sort it according to int. In fact,Comparator.comparing(User::getAge)
creates a comparator. By default It’s in ascending order. If you want descending order...just reverse itIt’s very comfortable...haha
Arrays.sort(list, (user1 , user2) -> Integer.compare(v1.age, v2.age));
In my opinion, you should implement the Comparable interface and then call sort directly