Create a sorted Set while using streams

后端 未结 4 853
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 04:06

I have a User class with name, type and age and then a long list of these users are my input List users = db.getUsers();<

4条回答
  •  心在旅途
    2021-01-12 04:44

    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 byAge = Comparator.comparingInt(User::getAge);
    
    Supplier> user = () -> new TreeSet(byAge);
    
    TreeSet userSet = users.stream().collect(Collectors.toCollection(user));
    

    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.

    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.

    Edit:

    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 set = new HashSet<>(users);   // remove duplicates via equals
    TreeSet userSet = set.stream().collect(Collectors.toCollection(user));
    

提交回复
热议问题