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