Using Comparator.comparing to sort an object by a list of objects, and then by the second property

First, I sorted the list by the attribute of the object (say, the user by his first name):

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

which I could replace with:

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

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

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

which seems to be working fine.

There is a message in the IDE: it can be replaced by Comparator.comparing ... but I don’t know how to do it. Is it possible? Something like this does not work:

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

How can I sort this using Comparator.comparing?

And after sorting by roleName, how can I sort by firstName as a second property?

+4
source share
1 answer

, :

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

:

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

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

Source: https://habr.com/ru/post/1692365/


All Articles