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)
三叔2017-06-23 09:15:33
The one upstairs is not friendly. The following method is more declarative, not the old imperative style
List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());
Isn’t it easier to read like this? Sort according to the age
attribute of User
. 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 it
List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());
It’s very comfortable...haha
ringa_lee2017-06-23 09:15:33
Arrays.sort(list, (user1 , user2) -> Integer.compare(v1.age, v2.age));
typecho2017-06-23 09:15:33
In my opinion, you should implement the Comparable interface and then call sort directly