Lambda收集器示例
Collectors常用方法
| 工厂方法 | 返回类型 | 作用 | 
|---|---|---|
| toSet | Set | 把流中所有项目收集到一个 Set,删除重复项 | 
| toList | List | 收集到一个 List 集合中 | 
| toCollection | Collection | 把流中所有项目收集到给定的供应源创建的集合 menuStream.collect(toCollection(), ArrayList::new) | 
| counting | Long | 计算流中元素的个数 | 
| summingInt | Integer | 对流中项目的一个整数属性求和 | 
| averagingInt | Double | 计算流中项目 Integer 属性的平均值 | 
| summarizingInt | IntSummaryStatistics | 收集关于流中项目 Integer 属性的统计值,例如最大、最小、 总和与平均值 | 
| joining | String | 连接对流中每个项目调用 toString 方法所生成的字符串 collect(joining(", ")) | 
| maxBy | Optional | 一个包裹了流中按照给定比较器选出的最大元素的 Optional, 或如果流为空则为 Optional.empty() | 
| minBy | Optional | 一个包裹了流中按照给定比较器选出的最小元素的 Optional, 或如果流为空则为 Optional.empty() | 
| reducing | 归约操作产生的类型 | 从一个作为累加器的初始值开始,利用 BinaryOperator 与流 中的元素逐个结合,从而将流归约为单个值累加 int totalCalories = menuStream.collect(reducing(0, Dish::getCalories, Integer::sum)); | 
| collectingAndThen | 转换函数返回的类型 | 包裹另一个收集器,对其结果应用转换函数 int howManyDishes = menuStream.collect(collectingAndThen(toList(), List::size)) | 
| groupingBy | Map<K, List> | 根据项目的一个属性的值对流中的项目作问组,并将属性值作 为结果 Map 的键 | 
| partitioningBy | Map<Boolean,List> | 根据对流中每个项目应用谓词的结果来对项目进行分区 | 
示例
Apple 类
public class Apple {
    private Integer id;
    private String name;
    private Integer num;
    private String color;
    public Apple() {}
    public Apple(Integer id, String name, Integer num, String color) {
        this.id = id;
        this.name = name;
        this.num = num;
        this.color = color;
    }
    // 省略 setter、getter方法
    @Override
    public String toString() {
        return "Apple{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", num=" + num +
                ", color='" + color + '\'' +
                '}';
    }
}
数据
List<Apple> appleList = new ArrayList<>();
Apple apple1 =  new Apple(1,"苹果1",10, "red");
Apple apple2 = new Apple(1,"苹果2",20, "green");
Apple apple3 =  new Apple(2,"香蕉",30, "yellow");
Apple apple4 =  new Apple(3,"荔枝",40, "red");
appleList.add(apple1);
appleList.add(apple2);
appleList.add(apple3);
appleList.add(apple4);
常用收集器示例
- toList
// 获取数量大于25的Apple
List<Apple> collect = appleList.stream()
                .filter(apple -> apple.getNum() > 25)
                .collect(toList());
//
[Apple{id=2, name='香蕉', num=30, color='yellow'},
 Apple{id=3, name='荔枝', num=40, color='red'}]
- toSet
// 获取颜色信息
Set<String> collect = appleList.stream()
                .map(Apple::getColor)
                .collect(toSet());
// [red, green, yellow]
- toCollection
List<Apple> collect = appleList.stream()
                .filter(x->x.getNum()>18)
                .collect(toCollection(ArrayList::new));
/-----------------------------/
[Apple{id=1, name='苹果2', num=20, color='green'},
 Apple{id=2, name='香蕉', num=30, color='yellow'},
 Apple{id=3, name='荔枝', num=40, color='red'}]
- counting:统计数量
Long aLong = appleList.stream()
                .filter(x -> x.getNum() > 18)
                .collect(counting());
// 另一种写法
Long aLong = appleList.stream()
                .filter(x -> x.getNum() > 18)
                .count();
// 3
- summingInt:对一个属性求和
Integer integer = appleList.stream()
                .collect(summingInt(p -> p.getNum()));
// 另一种写法
Integer integer = appleList.stream()
                .mapToInt(Apple::getNum).sum();
// 100
- averagingInt:求平均值
Double aDouble = appleList.stream().collect(averagingInt(Apple::getNum));
// 25.0
- summarizingInt:求最大、最小、平均值等
IntSummaryStatistics collect1 = appleList.stream().collect(summarizingInt(Apple::getNum));
// IntSummaryStatistics{count=4, sum=100, min=10, average=25.000000, max=40}
- joining:对流中元素调用toString,拼接成字符串
String s = appleList.stream().map(Apple::getName).collect(joining("--"));
// 苹果1--苹果2--香蕉--荔枝
- maxBy | minBy : 求最大最小元素
Optional<Apple> collect = appleList.stream()
                .collect(maxBy(comparing(Apple::getNum)));
// 另一种写法
Optional<Apple> collect = appleList.stream()
                .max(comparing(Apple::getNum))
// Apple{id=3, name='荔枝', num=40, color='red'}
- reducing:规约操作
Integer integer = appleList.stream()
                .collect(reducing(0, Apple::getNum, Integer::sum));
// 另一种写法
Optional<Integer> reduce = appleList.stream()
                .map(Apple::getNum)
                .reduce(Integer::sum);
// 100
- groupingBy | partitioningBy :分组操作
Map<Integer, List<Apple>> groupBy = appleList.stream()
                .collect(Collectors.groupingBy(Apple::getId));
// {
	1=[Apple{id=1, name='苹果1', num=10, color='red'},
     Apple{id=1, name='苹果2', num=20, color='green'}],
  2=[Apple{id=2, name='香蕉', num=30, color='yellow'}],
	3=[Apple{id=3, name='荔枝', num=40, color='red'}]}
// partitioningBy:条件分组
Map<Boolean, List<Apple>> collect1 = appleList.stream()
  					.collect(partitioningBy(x -> x.getNum() > 24));
// {
	false=[Apple{id=1, name='苹果1', num=10, color='red'},
         Apple{id=1, name='苹果2', num=20, color='green'}],
  true=[Apple{id=2, name='香蕉', num=30, color='yellow'},
        Apple{id=3, name='荔枝', num=40, color='red'}]}
Lambda收集器示例的更多相关文章
- Java基础学习总结(44)——10个Java 8 Lambda表达式经典示例
		Java 8 刚于几周前发布,日期是2014年3月18日,这次开创性的发布在Java社区引发了不少讨论,并让大家感到激动.特性之一便是随同发布的lambda表达式,它将允许我们将行为传到函数里.在Ja ... 
- 2020了你还不会Java8新特性?(五)收集器比较器用法详解及源码剖析
		收集器用法详解与多级分组和分区 为什么在collectors类中定义一个静态内部类? static class CollectorImpl<T, A, R> implements Coll ... 
- G1收集器-原创译文[未完成]
		G1收集器-原创译文 原文地址 Getting Started with the G1 Garbage Collector 目的 本文介绍了如何使用G1垃圾收集器以及如何与Hotspot JVM一起使 ... 
- [一] java8 函数式编程入门 什么是函数式编程 函数接口概念 流和收集器基本概念
		本文是针对于java8引入函数式编程概念以及stream流相关的一些简单介绍 什么是函数式编程? java程序员第一反应可能会理解成类的成员方法一类的东西 此处并不是这个含义,更接近是数学上的 ... 
- [四] java8 函数式编程 收集器浅析 收集器Collector常用方法 运行原理 内部实现
		Collector常见用法 常用形式为: .collect(Collectors.toList()) collect()是Stream的方法 Collectors 是收集器Collect ... 
- 垃圾收集器之:G1收集器
		G1垃圾收集器是一种工作在堆内不同分区上的并发收集器.分区既可以归属于老年代,也可以归属新生代,同一个代的分区不需要保持连续.为老年代设计分区的初衷是我们发现并发后台线程在回收老年代中没有引用的对象时 ... 
- 垃圾收集器之:CMS收集器
		HotSpot JVM的并发标记清理收集器(CMS收集器)的主要目标就是:低应用停顿时间.该目标对于大多数交互式应用很重要,比如web应用.在我们看一下有关JVM的参数之前,让我们简要回顾CMS收集器 ... 
- 垃圾收集器之:throughput吞吐量收集器
		在实践中我们发现对于大多数的应用领域,评估一个垃圾收集(GC)算法如何根据如下两个标准: 吞吐量越高算法越好 暂停时间越短算法越好 首先让我们来明确垃圾收集(GC)中的两个术语:吞吐量(through ... 
- Stream01 定义、迭代、操作、惰性求值、创建流、并行流、收集器、stream运行机制
		1 Stream Stream 是 Java 8 提供的一系列对可迭代元素处理的优化方案,使用 Stream 可以大大减少代码量,提高代码的可读性并且使代码更易并行. 2 迭代 2.1 需求 随机创建 ... 
随机推荐
- Linux_vim文本编辑器指令整理
			一般指令模式 : 可以移动光标,可以删除字符和删除整列,可以复制粘贴 编辑模式 : 按下"i, I, o, O, a, A, r, R"任意一个字母时进入;按下ESC退出编辑模式 ... 
- jxls实现动态图表
			此文章是基于 jxls实现基于excel模板的报表 一. 制作excel动态图表模板 1. 安装 excel 2003 ,新建文件,命名为:runRecord.xls 2. 创建两个表格,分别命名为: ... 
- 在C#中执行带有GO的批量sql语句
			引用 思海网络 在用C#中调用ADO执行批量SQL语句的时候,会出现无法识别GO语句的错误.这个时候,我们以GO语句为分割点,把整个批量语句分割成N块独立的SQL语句代码块(不包含GO语句),然后再 ... 
- Effective C++ .44 typename和class的不同
			在C++模板中的类型参数一般可以使用typename和class,两者没有什么不同.但是typename比class多项功能: “任何时候当你想要在template中指涉一个嵌套从属类型名称,就必须在 ... 
- es6 import笔记
			export输出: // profile.js var firstName = 'Michael'; var lastName = 'Jackson'; var year = 1958; export ... 
- bat中实现代码拷贝到指定目录后启动命令行并更改默认路径
			### window书写shell脚本,实现判断指定文件是否存在,存在就删除,然后复制新文件到此目录 ``` if exist "G:\test\test2\1.txt" (d ... 
- C#开发小技巧
			001.判断一个Form是否已关闭并释放,需要从引用和对象两方面来判断,判断引用是否为null:mainfm==null判断引用的对象是否已释放:mainfm.IsDisposedMainFormma ... 
- C++ *this与this的区别(系个人转载,个人再添加相关内容)
			转载地址:http://blog.csdn.net/stpeace/article/details/22220777 return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆 ... 
- Thinkphp中在本地测试很好,在服务器上出错,有可能是因为debug缓存的问题
			define('APP_DEBUG',false); 这个设置从true改为false后,一定要清空缓存,否则会出错. 
- 网络安全-使用HTTP动词篡改的认证旁路
			这个东西去年的安全扫描都没有,今天就扫出来了,非常奇怪的一个东西.好吧,找资料找原因.结果可能应为搜索名词的原因,这个问题在群友的帮助下解决了. 在我理解中servlet只有post和get方法,然后 ... 
