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