Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create two different compliementary lists using same input

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<User> users. Now I am trying to find the different User groups from ages according to the threshold. I tried this

List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());

This time it works I can see using

userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));

But I have to access the users list again to find the complimentary list. Can this not be done simpler?

like image 537
Mani Avatar asked Dec 20 '18 13:12

Mani


2 Answers

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);
like image 93
Ousmane D. Avatar answered Sep 27 '22 22:09

Ousmane D.


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);
like image 29
Naman Avatar answered Sep 27 '22 22:09

Naman