Java 8 Stream
1、关于Java8部分新特性介绍
Java8的新特性很多,在此就不一一介绍了,这里只说一下我自己在工作用用得比较多的几点:
1.1、Lambda表达式
Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中)
- 语法格式:
(parameters) -> expression 或者 (parameters) -> {statements;}
- PS:
(1)如果参数只有一个,可以不加圆括号
(2)不需要声明参数类型
(3)如果只有一条语句,可以不加花括号
(4)如果只有一条语句,编译器会自动将值返回;如果多条的话,需要手动return
1.2、方法引用
方法引用通过方法的名字来指向一个方法
- 语法格式:
方法引用使用一对冒号 ::
构造方法引用: 类::new
静态方法引用:类::静态方法
实例方法引用:类::实例方法 或者 对象::实例方法
1.3、Stream API
这个有点像Strom的处理方法(Spout和Blot),又有点像MapReduce(map和reduce)。用流的方式去处理,把一个集合元素转成一个一个的流,然后分别处理,最后再汇总。
1.4、接口中可以定义默认方法和静态方法
2、Stream API
- private List<CouponInfo> couponInfoList;
- private List<String> strList;
- private List<Integer> intList;
- @Before
- public void init() {
- CouponInfo couponInfo1 = new CouponInfo(123L, 10001, "5元现金券");
- CouponInfo couponInfo2 = new CouponInfo(124L, 10001, "10元现金券");
- CouponInfo couponInfo3 = new CouponInfo(125L, 10002, "全场9折");
- CouponInfo couponInfo4 = new CouponInfo(126L, 10002, "全场8折");
- CouponInfo couponInfo5 = new CouponInfo(127L, 10003, "全场7折");
- couponInfoList = new ArrayList<>();
- couponInfoList.add(couponInfo1);
- couponInfoList.add(couponInfo2);
- couponInfoList.add(couponInfo3);
- couponInfoList.add(couponInfo4);
- couponInfoList.add(couponInfo5);
- couponInfoList = new ArrayList<>();
- couponInfoList.add(couponInfo1);
- couponInfoList.add(couponInfo2);
- couponInfoList.add(couponInfo3);
- couponInfoList.add(couponInfo4);
- couponInfoList.add(couponInfo5);
- strList = Arrays.asList(new String[]{"A", "S", "D", "F", "X", "C", "Y", "H", "", null});
- intList = Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 6, 2, 3});
- }
2.1、forEach
- /**
- * 迭代 forEach
- */
- @Test
- public void testForEach() {
- strList.stream().forEach(System.out::println);
- strList.stream().forEach(e->System.out.print(e));
- System.out.println();
- strList.forEach(System.out::print);
- }
- A
- S
- D
- F
- X
- C
- Y
- H
- null
- ASDFXCYHnull
- ASDFXCYHnull
2.2、filter
- /**
- * 过滤 filter
- */
- @Test
- public void testFilter() {
- List<String> list = strList.stream().filter(x-> StringUtils.isNotBlank(x)).collect(Collectors.toList());
- System.out.println(list);
- List<Integer> list2 = intList.stream().distinct().collect(Collectors.toList());
- System.out.println(list2);
- List<CouponInfo> list3 = couponInfoList.stream().filter(x->x.getMerchantId() != 10001).collect(Collectors.toList());
- System.out.println(list3);
- }
- [A, S, D, F, X, C, Y, H]
- [1, 2, 3, 4, 5, 6]
- [CouponInfo{id=125, merchantId=10002, couponName='全场9折'}, CouponInfo{id=126, merchantId=10002, couponName='全场8折'}, CouponInfo{id=127, merchantId=10003, couponName='全场7折'}]
2.3、limit
- /**
- * limit
- */
- @Test
- public void testLimit() {
- List<String> list = strList.stream().limit(3).collect(Collectors.toList());
- System.out.println(list);
- }
- [A, S, D]
2.4、sorted
- /**
- * 排序 sorted
- */
- @Test
- public void testSorted() {
- List<Integer> list = intList.stream().sorted().collect(Collectors.toList());
- System.out.println(list);
- // 倒序
- List<Integer> list2 = intList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
- System.out.println(list2);
- List<String> list3 = strList.stream().sorted(Comparator.nullsLast(Comparator.naturalOrder())).collect(Collectors.toList());
- List<String> list4 = strList.stream().sorted(Comparator.nullsLast(Comparator.reverseOrder())).collect(Collectors.toList());
- System.out.println(list3);
- System.out.println(list4);
- List<CouponInfo> list5 = couponInfoList.stream().sorted(Comparator.comparing(CouponInfo::getId)).collect(Collectors.toList());
- List<CouponInfo> list6 = couponInfoList.stream().sorted(Comparator.comparing(CouponInfo::getId).reversed()).collect(Collectors.toList());
- List<Long> list51 = list5.stream().map(e->e.getId()).collect(Collectors.toList());
- List<Long> list61 = list6.stream().map(e->e.getId()).collect(Collectors.toList());
- System.out.println(list51);
- System.out.println(list61);
- }
- [1, 2, 2, 3, 3, 4, 5, 6, 6]
- [6, 6, 5, 4, 3, 3, 2, 2, 1]
- [, A, C, D, F, H, S, X, Y, null]
- [Y, X, S, H, F, D, C, A, , null]
- [123, 124, 125, 126, 127]
- [127, 126, 125, 124, 123]
2.5、map
- /**
- * map
- * 对每个元素进行处理,相当于MapReduce中的map阶段
- * Collectors.mapping()类似
- */
- @Test
- public void testMap() {
- List<Integer> list = intList.stream().map(e->2*e).collect(Collectors.toList());
- System.out.println(list);
- }
- [2, 4, 6, 8, 10, 12, 12, 4, 6]
2.6、toMap
- /**
- * 转成Map<K,V>
- *
- * 特别注意,key不能重复,如果重复的话默认会报错,可以指定key重复的时候怎么处理
- *
- * 例如:Map<String, Student> studentIdToStudent = students.stream().collect(toMap(Student::getId, Functions.identity());
- */
- @Test
- public void testToMap() {
- // 因为ID不重复,所以这里这么写没问题;但如果key换成CouponInfo::getMerchantId就有问题了
- Map<Long, CouponInfo> map = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getId, Function.identity()));
- // 这里重复的处理方式就是用后者覆盖前者
- Map<Integer, CouponInfo> map2 = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getMerchantId, Function.identity(), (c1, c2)->c2));
- Map<Integer, CouponInfo> map3 = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getMerchantId, Function.identity(),
- (c1, c2)->{if (c1.getId() > c2.getId()) {
- return c2;
- }else {
- return c1;
- }
- }));
- System.out.println(map);
- System.out.println(map2);
- System.out.println(map3);
- }
- {123=CouponInfo{id=123, merchantId=10001, couponName='5元现金券'}, 124=CouponInfo{id=124, merchantId=10001, couponName='10元现金券'}, 125=CouponInfo{id=125, merchantId=10002, couponName='全场9折'}, 126=CouponInfo{id=126, merchantId=10002, couponName='全场8折'}, 127=CouponInfo{id=127, merchantId=10003, couponName='全场7折'}}
- {10001=CouponInfo{id=124, merchantId=10001, couponName='10元现金券'}, 10002=CouponInfo{id=126, merchantId=10002, couponName='全场8折'}, 10003=CouponInfo{id=127, merchantId=10003, couponName='全场7折'}}
- {10001=CouponInfo{id=123, merchantId=10001, couponName='5元现金券'}, 10002=CouponInfo{id=125, merchantId=10002, couponName='全场9折'}, 10003=CouponInfo{id=127, merchantId=10003, couponName='全场7折'}}
2.6、groupingBy
- /**
- * 分组 groupingBy
- */
- @Test
- public void testGroupBy() {
- Map<Integer, List<CouponInfo>> map = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId));
- Map<Integer, Long> map2 = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId, Collectors.counting()));
- Map<Integer, Set<String>> map3 = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId, Collectors.mapping(CouponInfo::getCouponName, Collectors.toSet())));
- System.out.println(map);
- System.out.println(map2);
- System.out.println(map3);
- }
- {10001=[CouponInfo{id=123, merchantId=10001, couponName='5元现金券'}, CouponInfo{id=124, merchantId=10001, couponName='10元现金券'}], 10002=[CouponInfo{id=125, merchantId=10002, couponName='全场9折'}, CouponInfo{id=126, merchantId=10002, couponName='全场8折'}], 10003=[CouponInfo{id=127, merchantId=10003, couponName='全场7折'}]}
- {10001=2, 10002=2, 10003=1}
- {10001=[10元现金券, 5元现金券], 10002=[全场9折, 全场8折], 10003=[全场7折]}
2.7、summary
- /**
- * 数值统计
- */
- @Test
- public void testSum() {
- IntSummaryStatistics summaryStatistics = intList.stream().mapToInt(x->x).summaryStatistics();
- System.out.println(summaryStatistics.getMax());
- System.out.println(summaryStatistics.getMin());
- System.out.println(summaryStatistics.getAverage());
- System.out.println(summaryStatistics.getSum());
- }
- 6
- 1
- 3.5555555555555554
- 32
3、完整代码
- package com.cjs.boot.demo;
- import com.cjs.boot.domain.entity.CouponInfo;
- import org.apache.commons.lang3.StringUtils;
- import org.junit.Before;
- import org.junit.Test;
- import java.util.*;
- import java.util.function.Function;
- import java.util.stream.Collectors;
- public class StreamDemoTest {
- private List<CouponInfo> couponInfoList;
- private List<String> strList;
- private List<Integer> intList;
- @Before
- public void init() {
- CouponInfo couponInfo1 = new CouponInfo(123L, 10001, "5元现金券");
- CouponInfo couponInfo2 = new CouponInfo(124L, 10001, "10元现金券");
- CouponInfo couponInfo3 = new CouponInfo(125L, 10002, "全场9折");
- CouponInfo couponInfo4 = new CouponInfo(126L, 10002, "全场8折");
- CouponInfo couponInfo5 = new CouponInfo(127L, 10003, "全场7折");
- couponInfoList = new ArrayList<>();
- couponInfoList.add(couponInfo1);
- couponInfoList.add(couponInfo2);
- couponInfoList.add(couponInfo3);
- couponInfoList.add(couponInfo4);
- couponInfoList.add(couponInfo5);
- couponInfoList = new ArrayList<>();
- couponInfoList.add(couponInfo1);
- couponInfoList.add(couponInfo2);
- couponInfoList.add(couponInfo3);
- couponInfoList.add(couponInfo4);
- couponInfoList.add(couponInfo5);
- strList = Arrays.asList(new String[]{"A", "S", "D", "F", "X", "C", "Y", "H", "", null});
- intList = Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 6, 2, 3});
- }
- /**
- * 迭代 forEach
- */
- @Test
- public void testForEach() {
- strList.stream().forEach(System.out::println);
- strList.stream().forEach(e->System.out.print(e));
- System.out.println();
- strList.forEach(System.out::print);
- }
- /**
- * 过滤 filter
- */
- @Test
- public void testFilter() {
- List<String> list = strList.stream().filter(x-> StringUtils.isNotBlank(x)).collect(Collectors.toList());
- System.out.println(list);
- List<Integer> list2 = intList.stream().distinct().collect(Collectors.toList());
- System.out.println(list2);
- List<CouponInfo> list3 = couponInfoList.stream().filter(x->x.getMerchantId() != 10001).collect(Collectors.toList());
- System.out.println(list3);
- }
- /**
- * limit
- */
- @Test
- public void testLimit() {
- List<String> list = strList.stream().limit(3).collect(Collectors.toList());
- System.out.println(list);
- }
- /**
- * 排序 sorted
- */
- @Test
- public void testSorted() {
- List<Integer> list = intList.stream().sorted().collect(Collectors.toList());
- System.out.println(list);
- // 倒序
- List<Integer> list2 = intList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
- System.out.println(list2);
- List<String> list3 = strList.stream().sorted(Comparator.nullsLast(Comparator.naturalOrder())).collect(Collectors.toList());
- List<String> list4 = strList.stream().sorted(Comparator.nullsLast(Comparator.reverseOrder())).collect(Collectors.toList());
- System.out.println(list3);
- System.out.println(list4);
- List<CouponInfo> list5 = couponInfoList.stream().sorted(Comparator.comparing(CouponInfo::getId)).collect(Collectors.toList());
- List<CouponInfo> list6 = couponInfoList.stream().sorted(Comparator.comparing(CouponInfo::getId).reversed()).collect(Collectors.toList());
- List<Long> list51 = list5.stream().map(e->e.getId()).collect(Collectors.toList());
- List<Long> list61 = list6.stream().map(e->e.getId()).collect(Collectors.toList());
- System.out.println(list51);
- System.out.println(list61);
- }
- /**
- * map
- * 对每个元素进行处理,相当于MapReduce中的map阶段
- * Collectors.mapping()类似
- */
- @Test
- public void testMap() {
- List<Integer> list = intList.stream().map(e->2*e).collect(Collectors.toList());
- System.out.println(list);
- }
- /**
- * 转成Map<K,V>
- *
- * 特别注意,key不能重复,如果重复的话默认会报错,可以指定key重复的时候怎么处理
- *
- * 例如:Map<String, Student> studentIdToStudent = students.stream().collect(toMap(Student::getId, Functions.identity());
- */
- @Test
- public void testToMap() {
- // 因为ID不重复,所以这里这么写没问题;但如果key换成CouponInfo::getMerchantId就有问题了
- Map<Long, CouponInfo> map = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getId, Function.identity()));
- // 这里重复的处理方式就是用后者覆盖前者
- Map<Integer, CouponInfo> map2 = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getMerchantId, Function.identity(), (c1, c2)->c2));
- Map<Integer, CouponInfo> map3 = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getMerchantId, Function.identity(),
- (c1, c2)->{if (c1.getId() > c2.getId()) {
- return c2;
- }else {
- return c1;
- }
- }));
- System.out.println(map);
- System.out.println(map2);
- System.out.println(map3);
- }
- /**
- * 分组 groupingBy
- */
- @Test
- public void testGroupBy() {
- Map<Integer, List<CouponInfo>> map = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId));
- Map<Integer, Long> map2 = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId, Collectors.counting()));
- Map<Integer, Set<String>> map3 = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId, Collectors.mapping(CouponInfo::getCouponName, Collectors.toSet())));
- System.out.println(map);
- System.out.println(map2);
- System.out.println(map3);
- }
- /**
- * 数值统计
- */
- @Test
- public void testSum() {
- IntSummaryStatistics summaryStatistics = intList.stream().mapToInt(x->x).summaryStatistics();
- System.out.println(summaryStatistics.getMax());
- System.out.println(summaryStatistics.getMin());
- System.out.println(summaryStatistics.getAverage());
- System.out.println(summaryStatistics.getSum());
- }
- }
参考
http://ifeve.com/java-8-tutorial-2/
https://www.cnblogs.com/justcooooode/p/7701260.html
Java 8 Stream的更多相关文章
- Java 8 Stream API详解--转
原文地址:http://blog.csdn.net/chszs/article/details/47038607 Java 8 Stream API详解 一.Stream API介绍 Java8引入了 ...
- java之stream(jdk8)
一.stream介绍 参考: Java 8 中的 Streams API 详解 Package java.util.stream Java8初体验(二)Stream语法详解 二.例子 im ...
- Java 8 Stream API Example Tutorial
Stream API Overview Before we look into Java 8 Stream API Examples, let’s see why it was required. S ...
- Java笔记:Java 流(Stream)、文件(File)和IO
更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的 ...
- [零]java8 函数式编程入门官方文档中文版 java.util.stream 中文版 流处理的相关概念
前言 本文为java.util.stream 包文档的译文 极其个别部分可能为了更好理解,陈述略有改动,与原文几乎一致 原文可参考在线API文档 https://docs.oracle.com/jav ...
- java 11 Stream 加强
Stream 是 Java 8 中的新特性,Java 9 开始对 Stream 增加了以下 4 个新方法. 1) 增加单个参数构造方法,可为null Stream.ofNullable(null).c ...
- Java 8 新特性-菜鸟教程 (5) -Java 8 Stream
Java 8 Stream Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据. Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种 ...
- 关于java中Stream理解
关于java中Stream理解 Stream是什么 Stream:Java 8新增的接口,Stream可以认为是一个高级版本的Iterator.它代表着数据流,流中的数据元素的数量可以是有限的, 也可 ...
- java.util.stream 库简介
Java Stream简介 Java SE 8 中主要的新语言特性是拉姆达表达式.可以将拉姆达表达式想作一种匿名方法:像方法一样,拉姆达表达式具有带类型的参数.主体和返回类型.但真正的亮点不是拉姆达表 ...
随机推荐
- 1.QT中播放视频,录音程序的编写
1 通过process的方式播放视频 T22VideoPlayer.pro HEADERS += \ MyWidget.h SOURCES += \ MyWidget.cpp QT += gu ...
- 06 Activity隐式跳转
一,隐式跳转 某个Activity 需要在清单文件配置某个Activity如下信息: 注意:category要和action一起用 action:制定一个活动 在隐式跳转的可以用到 category ...
- SSH深度历险(九) Struts2+DWZ+Uploadify实现多文件(文件和图片等等)上传
在gxpt_uas系统中,要实现文件(文件和图片等等,可以灵活配置)的批量上传至mongodb,在学习这个过程中,学习了mongodb,并实现了批量上传的功能,实现思路:在DWZ的基础上参考官方的实例 ...
- android studio——Failed to set up SDK
最近使用android studio ,在IDE里面使用Gradle构建的时候,一直出现构建失败,失败信息显示Failed to set up SDK.然后 提示无法找到andriod-14平台,我更 ...
- Mybatis执行Executor(一)
在DefaultSqlSession中我们可以看到一系列的增删改查操作的其实都是在调用Executor的接口,Mybatis对外统一提供了一个操作接口类Executor,提供的接口方法有update. ...
- Android 面向协议编程 体会优雅编程之旅
Android中面向协议编程的深入浅出 http://blog.csdn.net/sk719887916/article/details skay编写 说起协议,现实生活中大家第一感觉会想到规则或者约 ...
- ROS_Kinetic_15 ROS使用Qt
ROS_Kinetic_15 ROS使用Qt 在网页http://www.qt.io/download-open-source/#section-2 下载并安装Qt ~/下载$ chmod +x qt ...
- 我也来写spring
本文可作为北京尚学堂 spring课程的学习笔记 我们还是用上一篇文章的例子 给数据库中增加一个user 整体代码如下 package com.bjsxt.test; import com.bjsxt ...
- GDAL书籍
GDAL的书籍经过快两年的编写修改,终于出版发行了,有需要的同学可以到下面的网址进行购买. 购买地址: 亚马逊:http://www.amazon.cn/GDAL%E6%BA%90%E7%A0%81% ...
- webview与js交互
对于android初学者应该都了解webView这个组件.之前我也是对其进行了一些简单的了解,但是在一个项目中不得不用webview的时候,发现了webview的强大之处,今天就分享一下使用we ...