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 中主要的新语言特性是拉姆达表达式.可以将拉姆达表达式想作一种匿名方法:像方法一样,拉姆达表达式具有带类型的参数.主体和返回类型.但真正的亮点不是拉姆达表 ...
随机推荐
- 精通CSS+DIV网页样式与布局--初探CSS
CSS英文名Cascading Style Sheet,中文名字叫层叠样式表,是用于控制页面样式并允许将样式信息与网页内容分离的一种标记性语言,DIV+CSS是WEB设计标准,它是一种网页的布局方法. ...
- MySQL 数据库开发的 36 条军规
MySQL 数据库开发的 36 条军规 写在前面的话: 总是在灾难发生后,才想起容灾的重要性: 总是在吃过亏后,才记得曾经有人提醒过. (一)核心军规 (1)不在数据库做运算:cpu计算务必移至业务层 ...
- Android项目-高考作文功能简介(一)
前言 : 开发安卓也已2年多了近3年了, 在自己刚入行的时候就有自己独立开发一个App的想法. 后来自己做了<<高考作文>>这一App. 后面续续断断的维护者. 也因为功能简 ...
- JAVA之旅(十一)——RuntimeException,异常的总结,Package,jar包,多线程概述
JAVA之旅(十一)--RuntimeException,异常的总结,Package,jar包,多程序概述 继续JAVA之旅 一.RuntimeException 在Exception种有一个特殊的子 ...
- naoting
生活就像一锅菠菜汤 20160714 夜
- EBS中内部银行相关API
来自:http://www.itpub.net/thread-1772135-1-1.html 1.创建银行 -- Create Bank DECLARE p_init_msg_list VARCHA ...
- 【Unity Shaders】Diffuse Shading——创建一个自定义的diffuse lighting model(漫反射光照模型)
本系列主要参考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同时会加上一点个人理解或拓展. 这里是本书所有的插图.这里是本书所需的代码和资源 ...
- 集群通信组件tribes之集群的平行通信
前面的集群成员维护服务为我们提供了集群内所有成员的地址端口等信息,可以通过MembershipService可以轻易从节点本地的成员列表获取集群所有的成员信息,有了这些成员信息后就可以使用可靠的TCP ...
- DrawerLayout实现网易新闻抽屉效果
个人感觉网易的客户端比较前卫,有很多新鲜的东西,有时候模仿这些好的客户端能学到很多东西 开始今天的主要课题,下面是网易客户端抽屉模式实现的效果 其实有个Drawerlayout这个布局,你得问题就已经 ...
- ubuntu14.04系统中virtualbox安装Oracle VM VirtualBox Extension Pack包
ubuntu14.04系统中virtualbox默认不支持usb设备,需要安装Oracle VM VirtualBox Extension Pack才行,但必须安装以下版本才可以安装成功: Oracl ...