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?
source
share