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

上一篇:电子表格控件Spreadsheet 对象方法事件详细介绍


下一篇:Linux 守护进程创建原理及简易方法