Java8 学习笔记-stream-collection(2)

这一遍是继上一篇collection的补充.

上篇, 我们创建了Map的一个实例, 但是不能适用于很多情况

Collectors.groupingBy()

String[] names3 = { "Larry", "Lati", "Moe", "Curly", "Mobi" };


        Stream.of(names3).collect(Collectors.groupingBy(b -> b.charAt(0)))
                .forEach((key, value) -> {
                    System.out.println("Key : " + key + " Value : " + value);
                });

输出:
Key : C Value : [Curly]
Key : L Value : [Larry, Lati]
Key : M Value : [Moe, Mobi]




Stream.of(names3)
                .collect(
                        Collectors.groupingBy(b -> b.charAt(0),
                                Collectors.counting()))
                .forEach((key, value) -> {
                    System.out.println("Key : " + key + " Value : " + value);
                });
输出:
Key : C Value : 1
Key : L Value : 2
Key : M Value : 2

再参考一下解释文档

* @see #groupingBy(Function, Collector)
  * @see #groupingBy(Function, Supplier, Collector)
  * @see #groupingByConcurrent(Function)
 */
public static <T, K> Collector<T, ?, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K> classifier) {
    return groupingBy(classifier, toList());
}

这里我们可以看见, 这里有三个method, 也就是有三种方式可供选择, 并且返回值为Map

  1. Function 分组的原则 , 参考工具Function类
    A1 A2 A3 B1 B2 B3
    function为first letter
    结果: A [A1,A2,A3] B [B1,B2,B3]
  2. Collector
  3. Supplier

这里来讨论下参数Collector, 也就是Collectors.method究竟是用来干啥的.
API文档

Implementations of Collector that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

这里说道, collectors是用于做 various useful reduction operations.
然而新的问题, reduction operation 是什么意思?
字典上的意思是, 减少,缩图等 ,可是意思还是说不通

官方文档中写着

The JDK contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations.

我认为是: 简化+组合的意思吧( 也就是具体操作的意思吧!? ), 不过这里, 理解为Map的value值产生的方式比较好.
看API文档, 有如下的操作

  • 集合: Accumulate(聚集),Group(分组) e.g toXXX
  • 字符串: 操作 e.g joining
  • 数字: summingInt
  • 布尔值: partitioningBy

回到正题, Collector和Supplier有什么用, Supplier相当于提供商, 也就是new object(),这一执行任务的对象, Collector则是该怎么处理数据, 这一个行为.
而Collectors.method 将上面两个行为结合在一起完成了, 也就是经常不需要Supplier这一参数啦


扩展学习:
mkyong-Java 8 – Stream Collectors groupingBy examples

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值