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