The partitioningBy collector applies a predicate to each element in a stream and produces a map from booleans to lists of elements from the stream that satisfied or didn't satisfy the predicate. For instance:
Stream.of(1,2,3,4).collect(partitioningBy(x -> x >= 3))
// {false=[1, 2], true=[3, 4]}
As discussed in What's the purpose of partitioningBy, the observed behavior is that partitioningBy always returns a map with entries for both true and false. E.g.:
Stream.empty().collect(partitioningBy(x -> false));
// {false=[], true=[]}
Stream.of(1,2,3).collect(partitioningBy(x -> false));
// {false=[1, 2, 3], true=[]}
Stream.of(1,2,3).collect(partitioningBy(x -> true));
// {false=[], true=[1, 2, 3]}
Is that behavior actually specified somewhere? The Javadoc only says:
Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a
Map<Boolean, List<T>>
. There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.
Could a conforming implementation return these instead:
Stream.empty().collect(partitioningBy(x -> false));
// {}, or {false=[]}, or {true=[]}
Stream.of(1,2,3).collect(partitioningBy(x -> false));
// {false=[1, 2, 3]}
Stream.of(1,2,3).collect(partitioningBy(x -> true));
// {true=[1, 2, 3]}
The corresponding JSR 335 only seems to include the same documentation, but not additional discussion about what entries the map will contain.
Collectors partitioningBy() method in Java 8 The partioningBy() method returns a Collector that partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.
Stream allMatch() Method The allMatch() method returns always a true or false , based on the result of the evaluation.
The partitioningBy() method always returns a Map with two entries - one for where the Predicate is true , and one for when it's false . Both entries can have empty lists, but they will be present.
First, we create a result map with two entries, one for each partition. The values are LinkedHashMap s so that insertion order is preserved. Then, we create a HashSet from the list, so that invoking set. contains(k) is a O(1) operation (otherwise, if we did list.
In Java 9 Javadoc of the method, there is a clarification which makes it more explicit:
The returned Map always contains mappings for both false and true keys.
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