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

user1386966 :

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?

Andy Turner :
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).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=427613&siteId=1