partitioningBy的目的是什么? [英] What's the purpose of partitioningBy
问题描述
例如,如果我打算对某些元素进行分区,我可以执行以下操作:
Stream.of(I ,Love,Stack Overflow)
.collect(Collectors.partitioningBy(s - > s.length()> 3))
.forEach((k,v) - > ; System.out.println(k +=>+ v));
输出:
false => [I]
true => [爱,堆栈溢出]
但对我来说 partioningBy
只是 groupingBy
的子句。虽然前者接受 Predicate
作为参数,而后者接受 Function
,我只看到一个分区作为正常的分组函数。
所以相同的代码完全相同:
Stream.of(I,Love,Stack Overflow)
.collect(Collectors.groupingBy(s - > s.length()> 3))
.forEach(() k,v) - > System.out.println(k +=>+ v));
这也导致 Map< Boolean,List< String>>
。
所以有什么理由我应该使用 partioningBy
而不是 groupingBy
?谢谢
partitioningBy
将始终返回包含两个条目的地图,一个对于谓词为真的位置和对于假位的位置。
两个条目都可能有空列表,但它们会存在。
这是 groupingBy
不会这样做,因为它只在需要时创建条目。
在极端情况下,如果你发送一个空流到 partitioningBy
你仍会在地图中获得两个条目,而 groupingBy
将返回一个空地图。
<编辑:编辑:如下所述,Java文档中未提及此行为,但更改它会消除
partitioningBy
当前提供的附加值。对于Java 9,这已经在规范中。 For example, if I intend to partition some elements, I could do something like:
Stream.of("I", "Love", "Stack Overflow")
.collect(Collectors.partitioningBy(s -> s.length() > 3))
.forEach((k, v) -> System.out.println(k + " => " + v));
which outputs:
false => [I]
true => [Love, Stack Overflow]
But for me partioningBy
is only a subcase of groupingBy
. Although the former accepts a Predicate
as parameter while the latter a Function
, I just see a partition as a normal grouping function.
So the same code does exactly the same thing:
Stream.of("I", "Love", "Stack Overflow")
.collect(Collectors.groupingBy(s -> s.length() > 3))
.forEach((k, v) -> System.out.println(k + " => " + v));
which also results in a Map<Boolean, List<String>>
.
So is there any reason I should use partioningBy
instead of groupingBy
? Thanks
partitioningBy
will always return a map with two entries, one for where the predicate is true and one for where it is false.
It is possible that both entries will have empty lists, but they will exist.
That's something that groupingBy
will not do, since it only creates entries when they are needed.
At the extreme case, if you send an empty stream to partitioningBy
you will still get two entries in the map whereas groupingBy
will return an empty map.
EDIT: As mentioned below this behavior is not mentioned in the Java docs, however changing it would take away the added value partitioningBy
is currently providing. For Java 9 this is already in the specs.
这篇关于partitioningBy的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!