Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a sorted Set while using streams

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?

like image 292
Mani Avatar asked Dec 19 '18 05:12

Mani


1 Answers

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

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<User> set = new HashSet<>(users);   // remove duplicates via equals
TreeSet<User> userSet = set.stream().collect(Collectors.toCollection(user));
like image 196
Tim Biegeleisen Avatar answered Sep 19 '22 14:09

Tim Biegeleisen