Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 259
Joshua Taylor Avatar asked Dec 22 '16 16:12

Joshua Taylor


People also ask

What is partitioningBy in java 8?

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

Which method will always return a map with two entries one for where the predicate is true and one for where it is false in streams API?

Stream allMatch() Method The allMatch() method returns always a true or false , based on the result of the evaluation.

Which method will always return a map with two entries one for where the predicate?

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.

How do I partition a map?

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.


1 Answers

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.

like image 136
user140547 Avatar answered Sep 28 '22 18:09

user140547