Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to divide a collection into 2 different collections?

I have a Set of numbers :

 Set<Integer> mySet = [ 1,2,3,4,5,6,7,8,9] 

I want to divide it into 2 sets of odds and evens.

My way was to use filter twice :

Set<Integer> set1 = mySet.stream().filter(y -> y % 2 == 0).collect(Collectors.toSet()) Set<Integer> set2 =mySet.stream().filter(y -> y % 2 != 0).collect(Collectors.toSet()) 

I don't like this solution because I go over the whole set twice.

Is there any smarter way to do it?

like image 787
user1386966 Avatar asked Feb 06 '18 17:02

user1386966


2 Answers

Map<Boolean, List<Integer>> partitioned =      set.stream().collect(Collectors.partitioningBy(x -> x%2 == 0)); 

The elements in partitioned.get(true) are even; the elements in partitioned.get(false) are odd.

Unlike doing this using groupingBy, it is guaranteed that both true and false lists will be present in the map even if they are empty. (Not documented in Java 8, but it was true; Java 9's doc now states it explicitly).

like image 123
Andy Turner Avatar answered Oct 04 '22 19:10

Andy Turner


You can use Collectors#partitioningBy like below.

Map<Boolean,List<Integer>> evenOddMap  = mySet.stream().collect(Collectors.partitioningBy(e -> e % 2 == 0)); System.out.println("Even : "+evenOddMap.get(true)); System.out.println("Odd : "+evenOddMap.get(false)); 
like image 21
Amit Bera Avatar answered Oct 04 '22 20:10

Amit Bera