Create a sorted Set while using streams

后端 未结 4 852
佛祖请我去吃肉
佛祖请我去吃肉 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:46

    Here's one way of doing it assuming you have equals and hashcode methods implemented in the User class properly.

    Set uniqueUsers = new HashSet<>(users);
    Set sortedUniqueUsers = uniqueUsers.stream()
        .sorted(Comparator.comparingInt(User::getAge))
        .collect(Collectors.toSet());
    

提交回复
热议问题