必须partitioningBy生成一个包含true和false条目的地图? [英] Must partitioningBy produce a map with entries for true and false?
问题描述
partitioningBy 收集器将谓词应用于流中的每个元素,并生成从布尔到满足或不满足谓词的流中元素列表的映射。例如:
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]}
正如分区的目的是什么所述,观察行为是 partitioningBy 始终返回包含 true 和 false 条目的地图。例如:
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]}
这种行为实际上是在某处指定的吗? Javadoc只说:
Is that behavior actually specified somewhere? The Javadoc only says:
返回一个收集器,它根据
Predicate对输入元素进行分区,并将它们组织成一个Map< Boolean,List< T>>
。对于返回的Map的类型,可变性,可序列化或
线程安全性,有
无保证。
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]}
相应的 JSR 335 似乎只包含相同的文档,但没有关于哪些条目的额外讨论地图将包含。
The corresponding JSR 335 only seems to include the same documentation, but not additional discussion about what entries the map will contain.
推荐答案
在方法的Java 9 Javadoc ,有一个澄清,使其更明确:
In Java 9 Javadoc of the method, there is a clarification which makes it more explicit:
返回的Map总是包含false和true键的映射。
The returned Map always contains mappings for both false and true keys.
这篇关于必须partitioningBy生成一个包含true和false条目的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!