使用流时创建排序集 [英] Create a sorted Set while using streams
问题描述
我有一个用户类名称,类型和年龄,然后这些用户的长列表是我的输入列表<用户> users = db.getUsers();
。
I have a User class with name, type and age and then a long list of these users are my input List<User> users = db.getUsers();
.
我正在尝试从中创建一组所有唯一身份用户,但问题是我正在寻找基于年龄对其进行排序也。我目前使用过 -
I am trying to create a set of all unique users from this, but the problem is I am looking for sorting them based on the age also. I have currently used-
Set<User> set = users.stream().collect(Collectors.toSet());
如何同时对此套装进行排序,任何想法?
How to sort this set at the same time as well, any idea?
推荐答案
在非排序集中谈论顺序是没有意义的。你应该使用类似 TreeSet
的东西,如果你想要按年龄排序的一套。
It doesn't make sense to speak of order within a non sorted set. You should be using something like TreeSet
if you want a set ordered by age.
Comparator<User> byAge = Comparator.comparingInt(User::getAge);
Supplier<TreeSet<User>> user = () -> new TreeSet<User>(byAge);
TreeSet<User> userSet = users.stream().collect(Collectors.toCollection(user));
如果上面的代码对你来说很难看,你也可以将你当前的用户组添加到 TreeSet
,但还有一个复制步骤。
If the above code be ugly to you, you could also just add your current set of users to a TreeSet
, but there would be one more copy step.
使用 TreeSet
和 LinkedHashSet
与维护排序顺序有关。使用 TreeSet
,在添加新用户时,将保留排序。使用 LinkedHashSet
,添加新用户可能会按年龄中断排序顺序,因为 LinkedHashSet
仅维护广告订单。
The main difference between using a TreeSet
and a LinkedHashSet
has to do with maintaining sorting order. With a TreeSet
, when adding new users, the sorting would be maintained. With a LinkedHashSet
, adding new users might break the sort order by age, because LinkedHashSet
only maintains insertion order.
修改:
根据以下@Federico的评论, TreeSet
actual将使用其比较器来确定 User
对象的相等性。如果您想首先通过 equals()
方法删除所有重复用户,那么我们可以先将所有用户添加到 HashSet
,然后使用上面的方法将它们添加到 TreeSet
。
Based on the comments by @Federico below, a TreeSet
actual would use its comparator to determine equality of User
objects. If you wanted to first remove all duplicate users by means of the equals()
method, then we can first add all users to a HashSet
, and then use the above approach to add them to a TreeSet
.
Set<User> set = new HashSet<>(users); // remove duplicates via equals
TreeSet<User> userSet = set.stream().collect(Collectors.toCollection(user));
这篇关于使用流时创建排序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!