美文网首页
Java 8 Stream Study

Java 8 Stream Study

作者: fdsun | 来源:发表于2020-09-23 16:53 被阅读0次

    Java 8 Stream Study

    Java 8 Stream

    Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。

    Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。

    Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

    这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。

    元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。

    +--------------------+       +------+   +------+   +---+   +-------+
    | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
    +--------------------+       +------+   +------+   +---+   +-------+
    
    • my笔记
    +--------------------+       +------+   +------+   +---+   
    | stream of elements +-----> |filter+-> |sorted+-> |map+-> ......
    +--------------------+       +------+   +------+   +---+   
                                 +------+   +------+   +---+   +-------+
                              -> |filter+-> |sorted+-> |map+-> |collect|
                                 +------+   +------+   +---+   +-------+
    

    以上的流程转换为 Java 代码为:

    List<Integer> transactionsIds = 
    widgets.stream()
                 .filter(b -> b.getColor() == RED)
                 .sorted((x,y) -> x.getWeight() - y.getWeight())
                 .mapToInt(Widget::getWeight)
                 .sum();
    

    什么是 Stream?

    Stream(流)是一个来自数据源的元素队列并支持聚合操作

    • 元素是特定类型的对象,形成一个队列。 Java中的Stream并不会存储元素,而是按需计算。
    • 数据源 流的来源。 可以是集合,数组,I/O channel, 产生器generator 等。
    • 聚合操作 类似SQL语句一样的操作, 比如filter, map, reduce, find, match, sorted等。

    和以前的Collection操作不同, Stream操作还有两个基础的特征:

    • Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。
    • 内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。

    生成流

    在 Java 8 中, 集合接口有两个方法来生成流:

    • stream() − 为集合创建串行流。
    • parallelStream() − 为集合创建并行流。
    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
    List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
    

    forEach

    Stream 提供了新的方法 'forEach' 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数:

    Random random = new Random(); 
    random.ints().limit(10).forEach(System.out::println);
    

    map

    map 方法用于映射每个元素到对应的结果,以下代码片段使用 map 输出了元素对应的平方数:

    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); 
    // 获取对应的平方数 
    List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
    

    filter

    filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串:

    List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); 
    // 获取空字符串的数量 
    long count = strings.stream().filter(string -> string.isEmpty()).count();
    

    limit

    limit 方法用于获取指定数量的流。 以下代码片段使用 limit 方法打印出 10 条数据:

    Random random = new Random(); 
    random.ints().limit(10).forEach(System.out::println);
    

    sorted

    sorted 方法用于对流进行排序。以下代码片段使用 sorted 方法对输出的 10 个随机数进行排序:

    Random random = new Random();
    random.ints().limit(10).sorted().forEach(System.out::println);
    

    并行(parallel)程序

    parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量:

    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); 
    // 获取空字符串的数量 
    long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
    

    我们可以很容易的在顺序运行和并行直接切换。


    Collectors

    Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:

    List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); 
    List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());  
    System.out.println("筛选列表: " + filtered); 
    String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); 
    System.out.println("合并字符串: " + mergedString);
    

    统计

    另外,一些产生统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上,它们可以用来产生类似如下的统计结果。

    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);  
    IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();  
    System.out.println("列表中最大的数 : " + stats.getMax()); 
    System.out.println("列表中最小的数 : " + stats.getMin()); 
    System.out.println("所有数之和 : " + stats.getSum()); 
    System.out.println("平均数 : " + stats.getAverage());
    

    stream的特点

    特点:

    1. 不是数据结构,不会保存数据。
    2. 不会修改原来的数据源,它会将操作后的数据保存到另外一个对象中。
    3. 惰性求值,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算。

    Stream操作分类

    Stream操作分类

    无状态:指元素的处理不受之前元素的影响;

    有状态:指该操作只有拿到所有元素之后才能继续下去。

    非短路操作:指必须处理所有元素才能得到最终结果;

    短路操作:指遇到某些符合条件的元素就可以得到最终结果,如 A || B,只要A为true,则无需判断B的结果。

    常用中间件

    filter:过滤流,过滤流中的元素,返回一个符合条件的Stream

    map:转换流,将一种类型的流转换为另外一种流。(mapToInt、mapToLong、mapToDouble 返回int、long、double基本类型对应的Stream)

    flatMap:简单的说,就是一个或多个流合并成一个新流。(flatMapToInt、flatMapToLong、flatMapToDouble 返回对应的IntStream、LongStream、DoubleStream流。)

    distinct:返回去重的Stream。

    sorted:返回一个排序的Stream。

    peek:主要用来查看流中元素的数据状态。

    limit:返回前n个元素数据组成的Stream。属于短路操作

    skip:返回第n个元素后面数据组成的Stream。

    结束操作

    forEach: 循环操作Stream中数据。

    toArray: 返回流中元素对应的数组对象。

    reduce: 聚合操作,用来做统计。

    collect: 聚合操作,封装目标数据。

    min、max、count: 聚合操作,最小值,最大值,总数量。

    anyMatch: 短路操作,有一个符合条件返回true。

    allMatch: 所有数据都符合条件返回true。

    noneMatch: 所有数据都不符合条件返回true。

    findFirst: 短路操作,获取第一个元素。

    findAny: 短路操作,获取任一元素。

    forEachOrdered: 暗元素顺序执行循环操作。

    具体用法

    1. 流的常用创建方法

    1.1 使用Collection下的 stream() 和 parallelStream() 方法

    List<String> list = new ArrayList<>();
    Stream<String> stream = list.stream(); //获取一个顺序流
    Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
    

    1.2 使用Arrays 中的 stream() 方法,将数组转成流

    Integer[] nums = new Integer[10];
    Stream<Integer> stream = Arrays.stream(nums);
    

    1.3 使用Stream中的静态方法:of()、iterate()、generate()

    Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
    Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(6);
    stream2.forEach(System.out::println); // 0 2 4 6 8 10
    Stream<Double> stream3 = Stream.generate(Math::random).limit(2);
    stream3.forEach(System.out::println);
    

    1.4 使用 BufferedReader.lines() 方法,将每行内容转成流

    BufferedReader reader = new BufferedReader(new FileReader("d:\\test_stream.txt"));
    Stream<String> lineStream = reader.lines();
    lineStream.forEach(System.out::println);
    

    1.5 使用 Pattern.splitAsStream() 方法,将字符串分隔成流

    Pattern pattern = Pattern.compile(",");
    Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");
    stringStream.forEach(System.out::println);
    

    2. 流的中间操作

    2.1 筛选与切片
    filter:过滤流中的某些元素
    limit(n):获取n个元素
    skip(n):跳过n元素,配合limit(n)可实现分页
    distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素

    Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
    Stream<Integer> newStream = stream.filter(s -> s > 5) //6 6 7 9 8 10 12 14 14
            .distinct() //6 7 9 8 10 12 14
            .skip(2) //9 8 10 12 14
            .limit(2); //9 8
    
    newStream.forEach(System.out::println);
    

    2.2 映射
    map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
    flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

    List<String> list = Arrays.asList("a,b,c", "1,2,3");
    
    //将每个元素转成一个新的且不带逗号的元素
    Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", ""));
    s1.forEach(System.out::println); // abc  123
    Stream<String> s3 = list.stream().flatMap(s -> {
        //将每个元素转换成一个stream
        String[] split = s.split(",");
        Stream<String> s2 = Arrays.stream(split);
        return s2;
    });
    
    s3.forEach(System.out::println); // a b c 1 2 3
    

    2.3 排序
    sorted():自然排序,流中元素需实现Comparable接口
    sorted(Comparator com):定制排序,自定义Comparator排序器

    List<String> list = Arrays.asList("aa", "ff", "dd");
    
    //String 类自身已实现Compareable接口
    list.stream().sorted().forEach(System.out::println);// aa dd ff
    
    Student s1 = new Student("aa", 10);
    Student s2 = new Student("bb", 20);
    Student s3 = new Student("aa", 30);
    Student s4 = new Student("dd", 40);
    
    List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
    
    //自定义排序:先按姓名升序,姓名相同则按年龄升序
    studentList.stream().sorted(
            (o1, o2) -> {
                if (o1.getName().equals(o2.getName())) {
                    return o1.getAge() - o2.getAge();
                } else {
                    return o1.getName().compareTo(o2.getName());
                }
            }
    ).forEach(System.out::println);
    

    2.4 消费
    peek:如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。

    Student s1 = new Student("aa", 10);
    Student s2 = new Student("bb", 20);
    
    List<Student> studentList = Arrays.asList(s1, s2);
    
    studentList.stream()
            .peek(o -> o.setAge(100))
            .forEach(System.out::println);   
    //结果:
    Student{name='aa', age=100}
    Student{name='bb', age=100}            
    

    3. 流的终止操作

    3.1 匹配、聚合操作
    allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
    noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
    anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
    findFirst:返回流中第一个元素
    findAny:返回流中的任意元素
    count:返回流中元素的总个数
    max:返回流中元素最大值
    min:返回流中元素最小值

    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    
    boolean allMatch = list.stream().allMatch(e -> e > 10); //false
    boolean noneMatch = list.stream().noneMatch(e -> e > 10); //true
    boolean anyMatch = list.stream().anyMatch(e -> e > 4);  //true
    
    Integer findFirst = list.stream().findFirst().get(); //1
    Integer findAny = list.stream().findAny().get(); //1
    
    long count = list.stream().count(); //5
    Integer max = list.stream().max(Integer::compareTo).get(); //5
    Integer min = list.stream().min(Integer::compareTo).get(); //1
    

    3.2 规约操作
    Optional<T> reduce(BinaryOperator<T> accumulator):第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
    T reduce(T identity, BinaryOperator<T> accumulator):流程跟上面一样,只是第一次执行时,accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
    <U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner):在串行流(stream)中,该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。

    //经过测试,当元素个数小于24时,并行时线程数等于元素个数,当大于等于24时,并行时线程数为16
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);
    Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
    System.out.println(v);   // 300
    Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
    System.out.println(v1);  //310
    Integer v2 = list.stream().reduce(0,
            (x1, x2) -> {
                System.out.println("stream accumulator: x1:" + x1 + "  x2:" + x2);
                return x1 - x2;
            },
            (x1, x2) -> {
                System.out.println("stream combiner: x1:" + x1 + "  x2:" + x2);
                return x1 * x2;
            });
    
    System.out.println(v2); // -300
    Integer v3 = list.parallelStream().reduce(0,
            (x1, x2) -> {
                System.out.println("parallelStream accumulator: x1:" + x1 + "  x2:" + x2);
                return x1 - x2;
            },
            (x1, x2) -> {
                System.out.println("parallelStream combiner: x1:" + x1 + "  x2:" + x2);
                return x1 * x2;
            });
    System.out.println(v3); //197474048
    

    3.3 收集操作
    collect:接收一个Collector实例,将流中元素收集成另外一个数据结构。
    Collector<T, A, R> 是一个接口,有以下5个抽象方法:
    Supplier<A> supplier():创建一个结果容器A
    BiConsumer<A, T> accumulator():消费型接口,第一个参数为容器A,第二个参数为流中元素T。
    BinaryOperator<A> combiner():函数接口,该参数的作用跟上一个方法(reduce)中的combiner参数一样,将并行流中各 个子进程的运行结果(accumulator函数操作后的容器A)进行合并。
    Function<A, R> finisher():函数式接口,参数为:容器A,返回类型为:collect方法最终想要的结果R。
    Set<Characteristics> characteristics():返回一个不可变的Set集合,用来表明该Collector的特征。有以下三个特征:
    CONCURRENT:表示此收集器支持并发。(官方文档还有其他描述,暂时没去探索,故不作过多翻译)
    UNORDERED:表示该收集操作不会保留流中元素原有的顺序。
    IDENTITY_FINISH:表示finisher参数只是标识而已,可忽略。

    3.3.1 Collector 工具库:Collectors

    Student s1 = new Student("aa", 10,1);
    Student s2 = new Student("bb", 20,2);
    Student s3 = new Student("cc", 10,3);
    
    List<Student> list = Arrays.asList(s1, s2, s3);
    //装成list
    List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]
    //转成set
    Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]
    //转成map,注:key不能相同,否则报错
    Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge)); // {cc=10, bb=20, aa=10}
    //这里要注意,如果你list转map的key如果不唯一,会报错,所以如果你不确定你的key是否唯一,可以改成如下:
    Map<Integer, String> map = persionList.stream().collect(
                    Collectors.toMap(Person::getAge, Person::getName, (key1, key2) -> key1)
            );
    //字符串分隔符连接
    String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
    
    //聚合操作
    //1.学生总数
    Long count = list.stream().collect(Collectors.counting()); // 3
    //2.最大年龄 (最小的minBy同理)
    Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 20
    //3.所有人的年龄
    Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge)); // 40
    //4.平均年龄
    Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge)); // 13.333333333333334
    // 带上以上所有方法
    DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
    
    System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
    
    //分组
    Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
    
    //多重分组,先根据类型分再根据年龄分
    Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));
    
    //分区
    //分成两部分,一部分大于10岁,一部分小于等于10岁
    Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
    
    //规约
    Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40
    

    3.3.2 Collectors.toList() 解析

    //toList 源码
    public static <T> Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
                (left, right) -> {
                    left.addAll(right);
                    return left;
                }, CH_ID);
    }
    
    //为了更好地理解,我们转化一下源码中的lambda表达式
    public <T> Collector<T, ?, List<T>> toList() {
        Supplier<List<T>> supplier = () -> new ArrayList();
        BiConsumer<List<T>, T> accumulator = (list, t) -> list.add(t);
        BinaryOperator<List<T>> combiner = (list1, list2) -> {
            list1.addAll(list2);
            return list1;
        };
    
        Function<List<T>, List<T>> finisher = (list) -> list;
        Set<Collector.Characteristics> characteristics = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
    
        return new Collector<T, List<T>, List<T>>() {
            @Override
            public Supplier supplier() {
                return supplier;
            }
    
            @Override
            public BiConsumer accumulator() {
                return accumulator;
            }
            
            @Override
            public BinaryOperator combiner() {
                return combiner;
            }
            @Override
            public Function finisher() {
                return finisher;
            }
    
            @Override
            public Set<Characteristics> characteristics() {
                return characteristics;
            }
        };
    }
    

    参考链接:

    1. Java 8 Stream
    2. java代码之美(2)
    3. Java 8 stream的详细用法
    4. 深入理解Java Stream流水线

    相关文章

      网友评论

          本文标题:Java 8 Stream Study

          本文链接:https://www.haomeiwen.com/subject/kqyoyktx.html