Must partitioningBy produce a map with entries for true and false?

Joshua Taylor :

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

user140547 :

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.

Guess you like

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