Java Streams learning path Level 1 This level · 13 of 25
Easy java streams

Partition numbers into even and odd

The 30 second answer

I use partitioningBy with a predicate for evenness. The result is always a map with both true and false keys, even when one side is empty. That is the main difference from groupingBy, which only creates keys that actually appear.

Could you say this in an interview?
Map<Boolean, List<Integer>> p = nums.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

The returned map always contains both true and false keys, even if one list is empty.

Sources (1)
  1. Collectors.partitioningBydocs.oracle.com
Previous
Next