lambda - java8 An object is arranged in the order of a certain field in the object
欧阳克
欧阳克 2017-06-23 09:13:33
0
3
1066

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)

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(3)
三叔

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_lee

Arrays.sort(list, (user1 , user2) -> Integer.compare(v1.age, v2.age));

typecho

In my opinion, you should implement the Comparable interface and then call sort directly

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template