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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With