partitioningBy的目的是什么 [英] What's the purpose of partitioningBy

查看:30
本文介绍了partitioningBy的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我打算对某些元素进行分区,则可以执行以下操作:

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));

输出:

false => [I]
true => [Love, Stack Overflow]

但对我来说partioningBy 只是groupingBy 的一个子案例.虽然前者接受一个Predicate作为参数,而后者接受一个Function,但我只是把一个partition看作是一个普通的分组函数.

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));

这也导致 Map>.

那么我有什么理由应该使用 partioningBy 而不是 groupingBy 吗?谢谢

So is there any reason I should use partioningBy instead of groupingBy? Thanks

推荐答案

partitioningBy 将始终返回一个包含两个条目的映射,一个用于谓词为真的地方,一个用于谓词为真的地方是假的.可能两个条目都有空列表,但它们会存在.

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.

这就是 groupingBy 不会做,因为它只在需要时创建条目.

That's something that groupingBy will not do, since it only creates entries when they are needed.

在极端情况下,如果您将空流发送到 partitioningBy 你仍然会在地图中得到两个条目,而 groupingBy 将返回一个空地图.

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.

如下所述,Java 文档中未提及此行为,但是更改它会带走附加值 partitioningBy 目前正在提供.对于 Java 9,这已经在规范中了.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆