• Stream流


    1、Stream概述

    Stream是将要处理的元素集合看作一种流,在流的过程中,借助Stream API对流中的元素进行操作,比如:筛选、排序、聚合等

    Stream可以由数组或集合创建,对流的操作分为两种:

        1、中间操作,每次返回一个新的流,可以有多个;

        2、终端操作,每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。

    特性:

    1、stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果;

    2、stream不会改变数据源,通常情况下回产生一个新的集合或一个值;

    3、stream具有延迟执行特性,只调用终端操作时,中间操作才会执行;

    2、Stream和parallelStream的简单区分:

    stream和parallelStream的简单区分:stream是顺序流,由主线程按顺序对流执行操作,而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。

    如果流综合你的数据量足够大,并行流可以加快处理速度。

    除了直接创建并行流,还可以通过parallel()把顺序流换成并行流;

    Optional findFirst = list.stream().parallel().filter(x->x>6).findFirst();
    

    3、Stream的使用

    在使用stream之前,先理解一个概念:Optional。

    Optional类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

    3.1 遍历/匹配(foreach/find/match)

    Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。

    3.2 筛选(filter)

    筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作

    3.3 聚合(max/min/count)

    3.4 映射(map/flatMap)

    映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatmap:

            map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。

            flatmap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连成一个流。

    3.5 归约(reduce)

    归约,也称缩减,是把一个流缩减成一个值,能实现对集合求和、求乘积和求和最值操作。

    1. public class StreamTest {
    2. public static void main(String[] args) {
    3. List list = Arrays.asList(1, 3, 2, 8, 11, 4);
    4. // 求和方式1
    5. Optional sum = list.stream().reduce((x, y) -> x + y);
    6. // 求和方式2
    7. Optional sum2 = list.stream().reduce(Integer::sum);
    8. // 求和方式3
    9. Integer sum3 = list.stream().reduce(0, Integer::sum);
    10. // 求乘积
    11. Optional product = list.stream().reduce((x, y) -> x * y);
    12. // 求最大值方式1
    13. Optional max = list.stream().reduce((x, y) -> x > y ? x : y);
    14. // 求最大值写法2
    15. Integer max2 = list.stream().reduce(1, Integer::max);
    16. System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);
    17. System.out.println("list求积:" + product.get());
    18. System.out.println("list求最大值:" + max.get() + "," + max2);
    19. }
    20. }

     

    1. public class StreamTest {
    2. public static void main(String[] args) {
    3. List personList = new ArrayList();
    4. personList.add(new Person("Tom", 8900, 23, "male", "New York"));
    5. personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
    6. personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
    7. personList.add(new Person("Anni", 8200, 24, "female", "New York"));
    8. personList.add(new Person("Owen", 9500, 25, "male", "New York"));
    9. personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
    10. // 求工资之和方式1:
    11. Optional sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
    12. // 求工资之和方式2:
    13. Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),
    14. (sum1, sum2) -> sum1 + sum2);
    15. // 求工资之和方式3:
    16. Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
    17. // 求最高工资方式1:
    18. Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
    19. Integer::max);
    20. // 求最高工资方式2:
    21. Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
    22. (max1, max2) -> max1 > max2 ? max1 : max2);
    23. // 求最高工资方式3:
    24. Integer maxSalary3 = personList.stream().map(Person::getSalary).reduce(Integer::max).get();
    25. System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);
    26. System.out.println("最高工资:" + maxSalary + "," + maxSalary2 + "," + maxSalary3);
    27. }
    28. }

     

    3.6 收集(collect)

    collect ,主要依赖java.util.stream.Collectors类内置的静态方法。

    3.6.1 归集(toList/toSet/toMap)

    因为流不存储数据,那么在流中的数据完成处理完,需要将流中的数据重新归集到新的集合里。toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。

    1. public class StreamTest {
    2. public static void main(String[] args) {
    3. List list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
    4. List listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
    5. Set set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
    6. List personList = new ArrayList();
    7. personList.add(new Person("Tom", 8900, 23, "male", "New York"));
    8. personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
    9. personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
    10. personList.add(new Person("Anni", 8200, 24, "female", "New York"));
    11. Map map = personList.stream().filter(p -> p.getSalary() > 8000)
    12. .collect(Collectors.toMap(Person::getName, p -> p));
    13. System.out.println("toList:" + listNew);
    14. System.out.println("toSet:" + set);
    15. System.out.println("toMap:" + map);
    16. }
    17. }

     运行结果:

    toList:[6, 4, 6, 6, 20]
    toSet:[4, 20, 6]
    toMap:{Tom=mutest.Person@5fd0d5ae, Anni=mutest.Person@2d98a335}

     3.6.2 统计(count/averaging)

    Collectors提供了一系列数据统计的静态方法:

            计数:count

            平均值:averagingInt、averagingLong、averagingDouble

            最值:maxBy、minBy

            求和:summingInt、summingLong、summingDouble

            统计以上所有:summarizingInt、summarizingLong、summarizingDouble

  • 相关阅读:
    园区组网配置实例
    Mybatis、MybatisPlus自定义返回单个Map集合
    电脑死机是什么原因及解决方法
    ardupilot 日志分析《xKF1信息》
    FlinkSQL系列07-表查询
    leetcode 221. 最大正方形
    ini文件的读取
    智能指针shared_from_this
    【LeetCode】【剑指offer】【剪绳子(二)】
    #### 广告投放 ####
  • 原文地址:https://blog.csdn.net/qq_45718545/article/details/134448696