加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java 8 Stream

发布时间:2020-12-15 06:53:51 所属栏目:Java 来源:网络整理
导读:1、关于Java8部分新特性介绍 Java8的新特性很多,在此就不一一介绍了,这里只说一下我自己在工作用用得比较多的几点: 1.1、Lambda表达式 Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中) 语法格式: (parameters) - expression 或者 (para

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

 1     private List<CouponInfo> couponInfoList;
 2 
 3     private List<String> strList;
 4 
 5     private List<Integer> intList;
 6 
 7     @Before
 8     public void init() {
 9         CouponInfo couponInfo1 = new CouponInfo(123L,10001,"5元现金券");
10         CouponInfo couponInfo2 = new CouponInfo(124L,"10元现金券"11         CouponInfo couponInfo3 = new CouponInfo(125L,10002,"全场9折"12         CouponInfo couponInfo4 = new CouponInfo(126L,"全场8折"13         CouponInfo couponInfo5 = new CouponInfo(127L,10003,"全场7折"14 
15         couponInfoList = new ArrayList<>();
16         couponInfoList.add(couponInfo1);
17         couponInfoList.add(couponInfo2);
18         couponInfoList.add(couponInfo3);
19         couponInfoList.add(couponInfo4);
20         couponInfoList.add(couponInfo5);
21 
22         couponInfoList = 23 24 25 26 27 28 
29         strList = Arrays.asList(new String[]{"A","S","D","F","X","C","Y","H","",null});
30 
31         intList = Arrays.asList(new Integer[]{1,2,3,4,5,6,332     }

2.1、forEach

/**
 2      * 迭代  forEach
 3      */
 4     @Test
 testForEach() {
 6         strList.stream().forEach(System.out::println);
 7         strList.stream().forEach(e->System.out.print(e));
 8         System.out.println();
 9         strList.forEach(System.out::print);
10     }
A
S
D
F
X
C
Y
H


ASDFXCYHnull
ASDFXCYHnull

?2.2、filter

     * 过滤  filter
 testFilter() {
 6         List<String> list = strList.stream().filter(x-> StringUtils.isNotBlank(x)).collect(Collectors.toList());
        System.out.println(list);
 8         List<Integer> list2 = intList.stream().distinct().collect(Collectors.toList());
        System.out.println(list2);
10         List<CouponInfo> list3 = couponInfoList.stream().filter(x->x.getMerchantId() != 10001).collect(Collectors.toList());
11         System.out.println(list3);
12     }
[A,S,D,F,X,C,Y,H]
[1,6]
[CouponInfo{id=125,merchantId=10002,couponName='全场9折'},CouponInfo{id=126,couponName='全场8折'},CouponInfo{id=127,merchantId=10003,couponName='全场7折'}]

2.3、limit

1     2      * limit
3      4 5      testLimit() {
6         List<String> list = strList.stream().limit(37 8     }
[A,D]

2.4、sorted

     * 排序  sorted
 testSorted() {
 6         List<Integer> list = intList.stream().sorted().collect(Collectors.toList());
 8         //  倒序
 9         List<Integer> list2 = intList.stream().sorted(Comparator.reverSEOrder()).collect(Collectors.toList());
10 11 
12         List<String> list3 = strList.stream().sorted(Comparator.nullsLast(Comparator.naturalOrder())).collect(Collectors.toList());
13         List<String> list4 = strList.stream().sorted(Comparator.nullsLast(Comparator.reverSEOrder())).collect(Collectors.toList());
14 15         System.out.println(list4);
16 
17         List<CouponInfo> list5 = couponInfoList.stream().sorted(Comparator.comparing(CouponInfo::getId)).collect(Collectors.toList());
18         List<CouponInfo> list6 = couponInfoList.stream().sorted(Comparator.comparing(CouponInfo::getId).reversed()).collect(Collectors.toList());
19         List<Long> list51 = list5.stream().map(e->e.getId()).collect(Collectors.toList());
20         List<Long> list61 = list6.stream().map(e->21         System.out.println(list51);
22         System.out.println(list61);
23     }
[1,1)">]
[6,1]
[,A,H,]
[Y,1)">]
[123,124,125,126,127]
[127,123]

2.5、map

     * map
 3      * 对每个元素进行处理,相当于MapReduce中的map阶段
     * Collectors.mapping()类似
 5       7      testMap() {
 8         List<Integer> list = intList.stream().map(e->2*e).collect(Collectors.toList());
10     }
[2,8,10,12,6]

2.6、toMap

     * 转成Map<K,V>
     *
     * 特别注意,key不能重复,如果重复的话默认会报错,可以指定key重复的时候怎么处理
 5      * 例如:Map<String,Student> studentIdToStudent = students.stream().collect(toMap(Student::getId,Functions.identity());
 7       9      testToMap() {
10           因为ID不重复,所以这里这么写没问题;但如果key换成CouponInfo::getMerchantId就有问题了
11         Map<Long,CouponInfo> map = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getId,Function.identity()));
12           这里重复的处理方式就是用后者覆盖前者
13         Map<Integer,CouponInfo> map2 = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getMerchantId,Function.identity(),(c1,c2)->c2));
14         Map<Integer,CouponInfo> map3 = couponInfoList.stream().collect(Collectors.toMap(CouponInfo::getMerchantId,1)">15                 (c1,c2)->{if (c1.getId() > c2.getId()) {
16                     return c2;
17                 }else {
18                      c1;
                }
        }));
        System.out.println(map);
        System.out.println(map2);
        System.out.println(map3);
24     }
{123=CouponInfo{id=123,merchantId=10001,couponName='5元现金券'},124=CouponInfo{id=124,couponName='10元现金券'},125=CouponInfo{id=125,126=CouponInfo{id=126,127=CouponInfo{id=127,couponName='全场7折'}}
{10001=CouponInfo{id=124,10002=CouponInfo{id=126,10003=CouponInfo{id=127,1)">}}
{10001=CouponInfo{id=123,10002=CouponInfo{id=125,couponName='全场7折'}}

2.6、groupingBy

     * 分组  groupingBy
 testGroupBy() {
 6         Map<Integer,List<CouponInfo>> map = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId));
 7         Map<Integer,Long> map2 = couponInfoList.stream().collect(Collectors.groupingBy(CouponInfo::getMerchantId,Collectors.counting()));
 8         Map<Integer,Set<String>> map3 =12     }
{10001=[CouponInfo{id=123,CouponInfo{id=124,couponName='10元现金券'}],10002=[CouponInfo{id=125,couponName='全场8折'}],10003=[CouponInfo{id=127,1)">}]}
{10001=2,10002=2,10003=1}
{10001=[10元现金券,5元现金券],10002=[全场9折,全场8折],10003=[全场7折]}

2.7、summary

     * 数值统计
 testSum() {
 6         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());
11     }
6
1
3.5555555555555554
32

3、完整代码

  1 package com.cjs.boot.demo;
  2 
  3 import com.cjs.boot.domain.entity.CouponInfo;
  4  org.apache.commons.lang3.StringUtils;
  5  org.junit.Before;
  6  org.junit.Test;
  7 
  8 import java.util.*;
  9  java.util.function.Function;
 10  java.util.stream.Collectors;
 11 
 12 class StreamDemoTest {
 13 
 14      15 
 16      17 
 18      19 
 20  21      22         CouponInfo couponInfo1 =  23         CouponInfo couponInfo2 =  24         CouponInfo couponInfo3 =  25         CouponInfo couponInfo4 =  26         CouponInfo couponInfo5 =  27 
 28         couponInfoList =  29  30  31  32  33  34 
 35         couponInfoList =  36  37  38  39  40  41 
 42         strList = Arrays.asList( 43 
 44         intList = Arrays.asList( 45     }
 46 
 47      48  49       50  51      52  53         strList.stream().forEach(e-> 54  55  56  57 
 58      59  60       61  62      63         List<String> list = strList.stream().filter(x-> 64  65         List<Integer> list2 = 66  67         List<CouponInfo> list3 = couponInfoList.stream().filter(x->x.getMerchantId() != 10001 68  69  70 
 71      72  73       74  75      76         List<String> list = strList.stream().limit(3 77  78  79 
 80      81  82       83  84      85         List<Integer> list = 86  87          88         List<Integer> list2 = 89  90 
 91         List<String> list3 = 92         List<String> list4 = 93  94  95 
 96         List<CouponInfo> list5 = 97         List<CouponInfo> list6 = 98         List<Long> list51 = list5.stream().map(e-> 99         List<Long> list61 = list6.stream().map(e->100 101 102 103 
104     105 106 107 108      109 110     111         List<Integer> list = intList.stream().map(e->2*112 113 114 
115     116 117 118 119 120 121      122 123     124         125         Map<Long,1)">126         127         Map<Integer,1)">128         Map<Integer,1)">129                 (c1,1)">130                     131                 }132                     133 134 135 136 137 138 139 
140     141 142      143 144     145         Map<Integer,1)">146         Map<Integer,1)">147         Map<Integer,1)">148 149 150 151 152 
153     154 155      156 157     158         IntSummaryStatistics summaryStatistics = intList.stream().mapToInt(x->159 160 161 162 163 164 
165 }

?

参考

http://ifeve.com/java-8-tutorial-2/

https://www.cnblogs.com/justcooooode/p/7701260.html

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读