Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
manu Avatar asked Mar 08 '23 03:03

manu


1 Answers

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));
like image 149
Eran Avatar answered Apr 07 '23 17:04

Eran