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

血红的双手。 提交于 2019-12-06 17:12:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41287517/must-partitioningby-produce-a-map-with-entries-for-true-and-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!