简体   繁体   中英

Using Comparator.comparing for sorting an object by a list of objects and then by a second property

I initially sorted a list by an attribute of an object (let's say a User by its firstName ) with:

Collections.sort(userList, (u1, u2) -> (u1.getFirstName()).compareTo(u2.getFirstName()));

which I was able to replace with:

Collections.sort(userList, Comparator.comparing(User::getFirstName));

But now the User has a list of Roles with a roleName each and I want to sort the list by the roleName of the Role of the User . I came up with this:

Collections.sort(userList, (u1, u2) -> (u1.getUserRoles().get(0).getRoleName()).compareTo(u2.getUserRoles().get(0).getRoleName()));

which seems to work fine.

In the IDE, there is now the message: Can be replaced with Comparator.comparing ... , but I do not know how to exactly do this. Is this even possible? Something like this don't work:

Collections.sort(userList, Comparator.comparing(User::getUserRoles.get(0).getRoleName());

How can I sort this with Comparator.comparing ?

And after sorting by roleName , how is it possible to sort by the firstName as a second property?

You can't use a method reference in this case, but you can use a lambda expression:

Collections.sort(userList, Comparator.comparing(u -> u.getUserRoles().get(0).getRoleName()));

To sort by two properties:

Collections.sort(userList, Comparator.comparing((Function<User,String>)u -> u.getUserRoles().get(0).getRoleName())
                                     .thenComparing(User::getFirstName));

or

Collections.sort(userList, Comparator.comparing((User u) -> u.getUserRoles().get(0).getRoleName())
                                     .thenComparing(User::getFirstName));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM