Java 8 stream的详细用法


转载自:https://blog.csdn.net/y_k_y/article/details/84633001

一、概述

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

特点:

        1 . 不是数据结构,不会保存数据。

        2. 不会修改原来的数据源,它会将操作后的数据保存到另外一个对象中。(保留意见:毕竟peek方法可以修改流中元素)

        3. 惰性求值,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算。

Java 8 函数式接口

3.3.1 Collector 工具库:Collectors

  1.   Student s1 = new Student("aa", 10,1);
  2.   Student s2 = new Student("bb", 20,2);
  3.   Student s3 = new Student("cc", 10,3);
  4.   List list = Arrays.asList(s1, s2, s3);
  5.    
  6.   //装成list
  7.   List ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]
  8.    
  9.   //转成set
  10.   Set ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]
  11.    
  12.   //转成map,注:key不能相同,否则报错
  13.   Map studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge)); // {cc=10, bb=20, aa=10}
  14.    
  15.   //字符串分隔符连接
  16.   String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
  17.    
  18.   //聚合操作
  19.   //1.学生总数
  20.   Long count = list.stream().collect(Collectors.counting()); // 3
  21.   //2.最大年龄 (最小的minBy同理)
  22.   Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 20
  23.   //3.所有人的年龄
  24.   Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge)); // 40
  25.   //4.平均年龄
  26.   Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge)); // 13.333333333333334
  27.   // 带上以上所有方法
  28.   DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
  29.   System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
  30.    
  31.   //分组
  32.   Map> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
  33.   //多重分组,先根据类型分再根据年龄分
  34.   Map>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));
  35.    
  36.   //分区
  37.   //分成两部分,一部分大于10岁,一部分小于等于10岁
  38.   Map> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
  39.    
  40.   //规约
  41.   Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40

3.3.2 Collectors.toList() 解析

    1.   //toList 源码
    2.   public static Collector> toList() {
    3.   return new CollectorImpl<>((Supplier>) ArrayList::new, List::add,
    4.   (left, right) -> {
    5.   left.addAll(right);
    6.   return left;
    7.   }, CH_ID);
    8.   }
    9.    
    10.   //为了更好地理解,我们转化一下源码中的lambda表达式
    11.   public Collector> toList() {
    12.   Supplier> supplier = () -> new ArrayList();
    13.   BiConsumer, T> accumulator = (list, t) -> list.add(t);
    14.   BinaryOperator> combiner = (list1, list2) -> {
    15.   list1.addAll(list2);
    16.   return list1;
    17.   };
    18.   Function, List> finisher = (list) -> list;
    19.   Set characteristics = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
    20.    
    21.   return new Collector, List>() {
    22.   @Override
    23.   public Supplier supplier() {
    24.   return supplier;
    25.   }
    26.    
    27.   @Override
    28.   public BiConsumer accumulator() {
    29.   return accumulator;
    30.   }
    31.    
    32.   @Override
    33.   public BinaryOperator combiner() {
    34.   return combiner;
    35.   }
    36.    
    37.   @Override
    38.   public Function finisher() {
    39.   return finisher;
    40.   }
    41.    
    42.   @Override
    43.   public Set characteristics() {
    44.   return characteristics;
    45.   }
    46.   };
    47.    
    48.