Java8 Stream详解~收集(collect)

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/495906.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CrawlSpider 详解

From&#xff1a;https://blog.csdn.net/weixin_37947156/article/details/75604163 CrawlSpider是爬取那些具有一定规则网站的常用的爬虫&#xff0c;它基于Spider并有一些独特属性 rules: 是Rule对象的集合&#xff0c;用于匹配目标网站并排除干扰parse_start_url: 用于爬取…

MFC中实现的画箭头算法 (Arrow in MFC)

在codeproject中寻找到一个这样的算法,在这里介绍一下 可以改变三角形大小,顶点角度,是否填充和填充颜色等 但是画出的箭头还是不够美观....呵呵,还好吧 其中填充是代表箭头内是否填充颜色 先来看声明和实现 //使用一个结构体来存储相关的信息//Defines the attributes of…

Java8 Stream详解~排序:sorted

sorted&#xff0c;中间操作。有两种排序&#xff1a; sorted()&#xff1a;自然排序&#xff0c;流中元素需实现Comparable接口 sorted(Comparator com)&#xff1a;Comparator排序器自定义排序 「案例&#xff1a;将员工按工资由高到低&#xff08;工资一样则按年龄由大到小…

英国上议院AI报告:没中美有钱,但我可以主导道德游戏规则设定

来源&#xff1a;网络大数据随着全球各国政府纷纷计划推出 AI 驱动下的未来&#xff0c;英国正准备承担一些学术和道德上的责任。最近&#xff0c;英国上议院 (House of Lords) 发布了一份183页的 报告《AI in the UK: ready, willing and able?》(《人工智能在英国&#xff1…

Java8 Stream详解~ 提取/组合

流也可以进行合并、去重、限制、跳过等操作。 public class StreamTest {public static void main(String[] args) {String[] arr1 { "a", "b", "c", "d" };String[] arr2 { "d", "e", "f", "g&…

Scrapy 下载器 中间件(Downloader Middleware)

Scrapy 下载器中间件官方文档&#xff1a;https://scrapy-chs.readthedocs.io/zh_CN/1.0/topics/downloader-middleware.html 官方 英文 文档&#xff1a;http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#topics-downloader-middleware Scrapy 扩展中间件…

15 个 JavaScript Web UI 库

转载http://news.csdn.net/a/20100519/218442.html 几乎所有的富 Web 应用都基于一个或多个 Web UI 库或框架&#xff0c;这些 UI 库与框架极大地简化了开发进程&#xff0c;并带来一致&#xff0c;可靠&#xff0c;以及高度交互性的用户界面。本文介绍了 15 个非常强大的 Java…

2018年技术展望--中文版

来源&#xff1a;199IT互联网数据中心每年&#xff0c;《埃森哲技术展望》报告融合顶尖技术研究团队、行业领袖以及全球数据调研结果&#xff0c;发布未来三年内或将对各行各业产生重大影响的技术趋势判断&#xff0c;作为企业布局新战略的指导。2018年的《埃森哲技术展望》报告…

CompletableFuture详解~创建实例

创建 CompletableFuture 对象实例我们可以使用如下几个方法&#xff1a; static CompletableFuture<U> completedFuture(U value)//使用forkjoin公共线程池 static CompletableFuture<Void> runAsync(Runnable runnable) static CompletableFuture<U> suppl…

彻底搞懂 Scrapy 的中间件

彻底搞懂Scrapy的中间件&#xff08;一&#xff09;&#xff1a;https://www.cnblogs.com/xieqiankun/p/know_middleware_of_scrapy_1.html 彻底搞懂Scrapy的中间件&#xff08;二&#xff09;&#xff1a;https://www.cnblogs.com/xieqiankun/p/know_middleware_of_scrapy_2.h…

华为:5G技术前景堪忧,运营商将很难从5G赚钱

来源&#xff1a;FT中文网、5G作者&#xff1a;卢卡斯、法尔兹丨英国《金融时报》。未来智能实验室是人工智能学家与科学院相关机构联合成立的人工智能&#xff0c;互联网和脑科学交叉研究机构。未来智能实验室的主要工作包括&#xff1a;建立AI智能系统智商评测体系&#xff0…

PostgreSQL最常见问题

PostgreSQL最常见问题 常见问题1.1)PostgreSQL 是什么&#xff1f;该怎么发音&#xff1f;1.2)PostgreSQL 的版权是什么&#xff1f;1.3)PostgreSQL 可以运行在哪些操作系统平台上&#xff1f;1.4)我从哪里能得到 PostgreSQL&#xff1f;1.5)我从哪里能得到对 PostgreSQL 的支…

解决log4j多个日志都写到一个文件

之前客户端程序由于Websockt包依赖的log4j&#xff0c;就用log4j写日志了&#xff0c;Web用的log4j2没毛病。用log4j的多个logger的日志都写到一个文件里了&#xff0c;查了很多资料都没解决。今天闲了解决一下。 最后好使的配置 # 设置日志根 log4j.rootLogger INFO,Except…

CompletableFuture详解~设置任务结果

CompletableFuture 提供以下方法&#xff0c;可以主动设置任务结果。 boolean complete(T value) boolean completeExceptionally(Throwable ex) 第一个方法&#xff0c;主动设置 CompletableFuture 任务执行结果&#xff0c;若返回 true&#xff0c;表示设置成功。如果返回 …

Scrapy 爬虫去重效率优化之 Bloom Filter的算法的对接

From&#xff1a;https://cloud.tencent.com/developer/article/1084962 Python分布式爬虫打造搜索引擎Scrapy精讲—将bloomfilter(布隆过滤器)集成到scrapy-redis中https://www.cnblogs.com/adc8868/p/7442306.html scrapy redis bloomfilter &#xff1a;https://github.co…

为什么 AI 工程师要懂一点架构?

作者 | 王咏刚&#xff08;公众号ID&#xff1a;ban-qing-ren&#xff09;AI 时代&#xff0c;我们总说做科研的 AI 科学家、研究员、算法工程师离产业应用太远&#xff0c;这其中的一个含义是说&#xff0c;搞机器学习算法的人&#xff0c;有时候会因为缺乏架构&#xff08;In…

深度优先搜索遍历与广度优先搜索遍历

深度优先遍历过程 1、图的遍历 和树的遍历类似&#xff0c;图的遍历也是从某个顶点出发&#xff0c;沿着某条搜索路径对图中每个顶点各做一次且仅做一次访问。它是许多图的算法的基础。 深度优先遍历和广度优先遍历是最为重要的两种遍历图的方法。它们对无向图和有…

CompletableFuture详解~CompletionStage

CompletableFuture 分别实现两个接口 Future与 CompletionStage。 Future 接口大家都比较熟悉&#xff0c;这里主要讲讲 CompletionStage。 CompletableFuture 大部分方法来自CompletionStage 接口&#xff0c;正是因为这个接口&#xff0c;CompletableFuture才有如此强大功能…

Python 异步 IO 、协程、asyncio、async/await、aiohttp

From &#xff1a;廖雪峰 异步IO &#xff1a;https://www.liaoxuefeng.com/wiki/1016959663602400/1017959540289152 Python Async/Await入门指南 &#xff1a;https://zhuanlan.zhihu.com/p/27258289 Python 生成器 和 yield 关键字&#xff1a;https://blog.csdn.net/free…

智能语音简史:这场技术革命从哪开始?

来源&#xff1a;与非网1952年&#xff0c;贝尔实验室&#xff08;Bell Labs&#xff09;制造一台6英尺高自动数字识别机“Audrey”&#xff0c;它可以识别数字0&#xff5e;9的发音&#xff0c;且准确度高达90&#xff05;以上。并且它对熟人的精准度高&#xff0c;而对陌生人…