collect,收集,可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。

1 归集(toList/toSet/toMap)

因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。toListtoSettoMap比较常用,另外还有toCollectiontoConcurrentMap等复杂一些的用法。

下面用一个案例演示toListtoSettoMap

public class StreamTest {public static void main(String[] args) {List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());List<Person> personList = new ArrayList<Person>();personList.add(new Person("Tom", 8900, 23, "male", "New York"));personList.add(new Person("Jack", 7000, 25, "male", "Washington"));personList.add(new Person("Lily", 7800, 21, "female", "Washington"));personList.add(new Person("Anni", 8200, 24, "female", "New York"));Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p));System.out.println("toList:" + listNew);System.out.println("toSet:" + set);System.out.println("toMap:" + map);}
}

2 统计(count/averaging)

Collectors提供了一系列用于数据统计的静态方法:

  • 计数:count

  • 平均值:averagingIntaveragingLongaveragingDouble

  • 最值:maxByminBy

  • 求和:summingIntsummingLongsummingDouble

  • 统计以上所有:summarizingIntsummarizingLongsummarizingDouble

「案例:统计员工人数、平均工资、工资总额、最高工资。」

public class StreamTest {public static void main(String[] args) {List<Person> personList = new ArrayList<Person>();personList.add(new Person("Tom", 8900, 23, "male", "New York"));personList.add(new Person("Jack", 7000, 25, "male", "Washington"));personList.add(new Person("Lily", 7800, 21, "female", "Washington"));// 求总数Long count = personList.stream().collect(Collectors.counting());// 求平均工资Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));// 求最高工资Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));// 求工资之和Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));// 一次性统计所有信息DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));System.out.println("员工总数:" + count);System.out.println("员工平均工资:" + average);System.out.println("员工工资总和:" + sum);System.out.println("员工工资所有统计:" + collect);}
}

3 分组(partitioningBy/groupingBy)

  • 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。

  • 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。

「案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组」

public class StreamTest {public static void main(String[] args) {List<Person> personList = new ArrayList<Person>();personList.add(new Person("Tom", 8900, "male", "New York"));personList.add(new Person("Jack", 7000, "male", "Washington"));personList.add(new Person("Lily", 7800, "female", "Washington"));personList.add(new Person("Anni", 8200, "female", "New York"));personList.add(new Person("Owen", 9500, "male", "New York"));personList.add(new Person("Alisa", 7900, "female", "New York"));// 将员工按薪资是否高于8000分组Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));// 将员工按性别分组Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));// 将员工先按性别分组,再按地区分组Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));System.out.println("员工按薪资是否大于8000分组情况:" + part);System.out.println("员工按性别分组情况:" + group);System.out.println("员工按性别、地区:" + group2);}
}

4 接合(joining)

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

public class StreamTest {public static void main(String[] args) {List<Person> personList = new ArrayList<Person>();personList.add(new Person("Tom", 8900, 23, "male", "New York"));personList.add(new Person("Jack", 7000, 25, "male", "Washington"));personList.add(new Person("Lily", 7800, 21, "female", "Washington"));String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));System.out.println("所有员工的姓名:" + names);List<String> list = Arrays.asList("A", "B", "C");String string = list.stream().collect(Collectors.joining("-"));System.out.println("拼接后的字符串:" + string);}
}

5 归约(reducing)

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

public class StreamTest {public static void main(String[] args) {List<Person> personList = new ArrayList<Person>();personList.add(new Person("Tom", 8900, 23, "male", "New York"));personList.add(new Person("Jack", 7000, 25, "male", "Washington"));personList.add(new Person("Lily", 7800, 21, "female", "Washington"));// 每个员工减去起征点后的薪资之和(这个例子并不严谨,但一时没想到好的例子)Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));System.out.println("员工扣税薪资总和:" + sum);// stream的reduceOptional<Integer> sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);System.out.println("员工薪资总和:" + sum2.get());}
}

Java8 Stream详解~收集(collect)相关推荐

  1. Java8 Stream详解~映射(map/flatMap)

    映射,可以将一个流的元素按照一定的映射规则映射到另一个流中.分为map和flatMap: map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素. flatMap:接收一个 ...

  2. Java8 Stream详解~筛选:filter

    筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作. 「案例一:筛选出Integer集合中大于7的元素,并打印出来」 public class StreamTest {publ ...

  3. Java8 Stream详解~ 提取/组合

    流也可以进行合并.去重.限制.跳过等操作. public class StreamTest {public static void main(String[] args) {String[] arr1 ...

  4. Java8 Stream详解~排序:sorted

    sorted,中间操作.有两种排序: sorted():自然排序,流中元素需实现Comparable接口 sorted(Comparator com):Comparator排序器自定义排序 「案例:将 ...

  5. Java8 Stream详解~归约(reduce)

    归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和.求乘积和求最值操作. 「案例一:求Integer集合的元素之和.乘积和最大值.」 public class StreamTest { ...

  6. Java8 Stream详解~聚合(max/min/count)

    max.min.count这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计.Java stream中也引入了这些概念和用法,极大地方便了我们对集合.数组的数据统计工作. 「案例一:获 ...

  7. Java8 Stream详解~遍历/匹配(foreach/find/match)

    Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的.Stream的遍历.匹配非常简单. // import已省略,请自行添加,后面代码亦是publi ...

  8. Java8 Stream详解~Stream 创建

    Stream可以通过集合数组创建. 1.通过 java.util.Collection.stream() 方法用集合创建流 List<String> list = Arrays.asLis ...

  9. Java8 Stream详解~Stream概述

    Java 8 是一个非常成功的版本,这个版本新增的Stream,配合同版本出现的 Lambda ,给我们操作集合(Collection)提供了极大的便利. 那么什么是Stream? Stream将要处 ...

最新文章

  1. Statement与PreparedStatement区别
  2. IT人员健康信号之舌苔
  3. ubuntu 14.04安装mysql数据库
  4. selenium与chromedriver的操作
  5. hyperkube记录
  6. 7款颜值当道的 Linux 操作系统 !
  7. 【3D建模制作技巧分享】3dmax如何设置视图布局
  8. SYSLINUX 中文简介(怎样使用)
  9. 看病(版权所有翻版必究)
  10. linux下的oracle安装
  11. 10个我经常逛的“小网站”
  12. 亮度、饱和度、对比度、灰度 RGBHSV
  13. 在Python里,用股票案例讲描述性统计分析方法(内容来自我的书)
  14. chrome浏览器中自带input样式input:-internal-autofill-selected(修改input背景色)
  15. 数据仓库Hive编程——HiveQL的数据定义(一):Hive中的数据库
  16. 使用扫码枪扫码二维码并采集二维码信息
  17. 关于ie下阻止ActiveX控件
  18. Nginx之反向代理(三)
  19. 操作系统导论OSTEP 第七章作业答案 进程调度:介绍
  20. 一分钟带你认识最强大的数字可视化工具:微软Power BI

热门文章

  1. 论文浅尝 | 面向简单知识库问答的模式修正强化策略
  2. Selenium爬虫
  3. 语言资源的类别、搜索与搭建策略
  4. PHP+MySQL 跨服务器跨数据库数据拷贝系统
  5. JMeter4.0以上 分布式测试报错 server failed start Listen failed on port
  6. JConsole连接远程linux服务器配置
  7. unittest单元测试笔记
  8. c# ref和out参数
  9. JavaScript跳转到页面某个锚点#
  10. [转载]SQL SERVER 2008 阻止保存要求重新创建表的更改