简体   繁体   English

使用Comparator.comparing按对象列表排序对象,然后使用第二个属性

[英]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: 我最初按一个对象的属性(比如一个用户firstName )对列表进行排序:

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. 在IDE中,现在有消息: 可以用Comparator.comparing替换... ,但我不知道如何正确地执行此操作。 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 ? 如何使用Comparator.comparing对此进行排序?

And after sorting by roleName , how is it possible to sort by the firstName as a second property? 在按roleName排序之后,如何将firstName排序为第二个属性?

You can't use a method reference in this case, but you can use a lambda expression: 在这种情况下,您不能使用方法引用,但可以使用lambda表达式:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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