How do I create two different compliementary lists using same input

前端 未结 2 1073
轮回少年
轮回少年 2021-01-12 14:18

In my previous question - How to filter the age while grouping in map with list I was able to find the name to age groups using List users. Now I am

相关标签:
2条回答
  • 2021-01-12 14:59

    List.removeAll

    You can use removeAll to obtain the complimentary list.

    List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
    userBelowThreshold.removeAll(userAboveThreshold);
    

    Note: This would require overridden equals and hashCode implementation for User.


    Collectors.partitioningBy

    On the other hand, if you further want to iterate over the complete users list just once, you can use Collectors.partitioningBy as:

    Map<Boolean, List<User>> userAgeMap = users.stream()
            .collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
    List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
    List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);
    
    0 讨论(0)
  • 2021-01-12 15:18

    You're after the partitioningBy collector:

    Map<Boolean, List<User>> result = 
                 users.stream().collect(partitioningBy(u -> u.getAge() > 21));
    

    Then use it as follows:

    List<User> userAboveThreshold = result.get(true);
    List<User> userBelowThreshold = result.get(false);
    
    0 讨论(0)
提交回复
热议问题