Java集合框架 流 Streams| Mapping| Filtering| Slicing | Sorting |Reducing | Collectors|...

Posted 11biscuits

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java集合框架 流 Streams| Mapping| Filtering| Slicing | Sorting |Reducing | Collectors|...相关的知识,希望对你有一定的参考价值。

Main.java

package Stream;

public class Main {
    public static void main(String[]argv){
        StreamDemo.show();
    }
}

Movie.java

package Stream;

public class Movie implements Comparable<Movie>{
    private int likes;
    private String name;
    public Movie(String name,int likes){
        this.name=name;
        this.likes=likes;
    }
    public int getLikes(){
        return likes;
    }

    @Override
    public int compareTo(Movie o) {
        return this.getLikes()-o.getLikes();
    }

    public String getName() {
        return name;
    }
}

StreamDemo.java

package Stream;


import java.util.*;
import java.util.stream.*;

/*Contents:
* Streams
* Mapping
* Filtering
* Slicing
* Sorting
* Reducing
* Collectors
* ...
* */
public class StreamDemo {
    public static void show(){
        List<Movie>movies=List.of(
                new Movie("b",10),
                new Movie("a",15),
                new Movie("c",20)
        );
        int count=0;
        for(var movie:movies){
            if(movie.getLikes()>10){
                count++;
            }
        }
        System.out.println(count);//output 2
        //Declarative(Function) Programming
        //获得集合的流
        var count1=movies.stream().count();
        var count2=movies.stream().filter(movie -> {return movie.getLikes()>10;}).count();
        System.out.println(count1);//3
        System.out.println(count2);//2
        //获得数组流
        int[]numbers={1,2,3,4,5,6,7,8,9};
        Arrays.stream(numbers).forEach((int n)->{System.out.println(n+1);});

        /*如何创建流对象*/
        var stream=Stream.generate(()->Math.random());
        //使用流对象
        stream.limit(3).forEach(n->System.out.println(n));//输出三个随机数
        //生成有限流
        Stream.iterate(1,n->n+1).limit(10).forEach(n->System.out.println(n));
        //起始值为1 以后每个元素比前一个元素+1

        /*stream map 映射*/
        movies.stream().map(movie->{return movie.getLikes();}).forEach(
                like->System.out.println(like)
        );
        /*当集合存储集合时使用flatMap*/
        var stream1=Stream.of(
                List.of(1,2,3),
                List.of(4,5,6));
        //Stream<List<x>> -> Stream<x>
        stream1.flatMap(list->list.stream())
                .forEach(list->System.out.println(list));


        /*Filtering Elements*/
        movies.stream()
                .filter(movie ->  movie.getLikes()>10).
                forEach(movie -> {System.out.println("filter--"+movie.getLikes());});

        /*stream的方法分为两种
        * Intermediate(产生新的流通道)     Terminal(不产生新的流通道)
        *  map                           forEach
        *  flatMap
        *   filter
        * */


        /*Slicing a Stream*/
        //limit(n)    skip(n)   takeWhile(predicate) dropWhile(predicate)

        /*limit(n)*/
        movies.stream().limit(2)
                .forEach(movie->System.out.println("limit--"+movie.getLikes()));
        /*skip(n)*/
        movies.stream().skip(2)
                .forEach(movie -> System.out.println("movie--"+movie.getLikes()));
        /*takeWhile(Predicate)*/
        movies.stream().takeWhile(movie -> movie.getLikes()!=15)
                .forEach(movie -> System.out.println("takeWhile--"+movie.getLikes()));

        /*Sorting Stream*/
        //sorting comparable interface
        movies.stream().sorted().forEach(movie -> {System.out.println(movie.getLikes());});
        //sorting comparator
        movies.stream().sorted((a,b)->a.getName().compareTo(b.getName()))
                .forEach(movie -> System.out.println("comparator--"+movie.getName()));
        //sorting comparator comparing
        movies.stream().sorted(Comparator.comparing(movie->movie.getName()))
                //movies.stream().sorted(Comparator.comparing(Movie::getName))
                .forEach(movie -> System.out.println("comparator.comparing--"+movie.getName()));
        //倒序排序
        movies.stream().sorted(Comparator.comparing(Movie::getName).reversed())
                //movies.stream().sorted(Comparator.comparing(Movie::getName))
                .forEach(movie -> System.out.println("comparator.comparing reversed--"+movie.getName()));

        //Getting Distinct Elements
        List<Movie>movies1=List.of(
                new Movie("d",10),
                new Movie("b",10),
                new Movie("a",15),
                new Movie("c",20)
        );
        movies1.stream()
                .map(Movie::getLikes)
                .distinct()
                .forEach(System.out::println);
        /*10 15 20*/


        //Peeking Elements 中途去干些什么
        movies.stream().filter(m->m.getLikes()>10)
                .peek(movie -> System.out.println("filter later--"+movie.getLikes()))
                .map(Movie::getName)
                .peek(Name->System.out.println("map Name later--"+Name))
                .forEach(System.out::println);
        /*a c*/






        /*REDUCERS*/
        /*count()
        * anyMatch(Predicate)
        * allMatch(Predicate)
        * noneMatch(Predicate)
        * findFirst()
        * findAny()
        * max(comparator)
        * min(comparator)
        * */
        List<Movie>movies2=List.of(
                new Movie("d",10),
                new Movie("b",10),
                new Movie("a",15),
                new Movie("c",20)
        );
        //统计全部数量
        movies2.stream().count();
        //统计满足条件的数量
        movies2.stream().anyMatch(m->m.getLikes()>10);
        //检测所有是否都满条件
        movies2.stream().allMatch(m->m.getLikes()>10);
        //检测是否没有元素满足条件
        movies2.stream().noneMatch(m->m.getLikes()>10);
        //max
        movies2.stream().max(
                Comparator.comparing(Movie::getName)
        ).get().getName();
        //min
        movies2.stream().min(
                Comparator.comparing(Movie::getName)
        ).get().getName();
        //reduce
        Optional<Integer> sum=movies2.stream().map(m->m.getLikes())
                .reduce((a,b)->a+b);
        System.out.println(sum.get());//当没有值时将会返回null
        System.out.println(sum.orElse(0));//当没有值时将会返回0


        //Collectors
        List<Movie> over10movies=movies2.stream()
                .filter(m->m.getLikes()>10)
                .collect(Collectors.toList());
        Map<String,Integer> mapMovies=movies2.stream()
                .collect(Collectors.toMap(m->m.getName(),m->m.getLikes()));
        Double summarizingdouble=movies2.stream().collect(
                Collectors.summingDouble(m->m.getLikes())
        );
        System.out.println(summarizingdouble);
        String summarizingstring=movies2.stream()
                .map(m->m.getName())
                .collect(
                Collectors.joining(",")
        );//d,b,a,c
        System.out.println(summarizingstring);

        //Grouping Elements 分组
        var GroupingResult=movies2.stream()
                .collect(Collectors.groupingBy(Movie::getLikes));
        // Type of GroupingResult: Map<Integer,List<Movie>>
        /*
        movies2.stream()
                .collect(Collectors.groupingBy(Movie::getLikes,Collector.toSet()));
        Type of GroupingResult: Map<Integer,Set<Movie>>
        */
        var resultString=movies2.stream()
                .collect(Collectors.groupingBy(Movie::getLikes,Collectors.mapping(
                        Movie::getName,Collectors.joining(",")
                )));
        /*resultString Type Map<Integer,String>*/


        /*Partitioning Elements 划分元素*/
        var result11=movies2.stream().collect(
            Collectors.partitioningBy(m->m.getLikes()>20)
        );
        /*result11 type: Map<Boolean,List<Movie>>*/
        var result22=movies2.stream().collect(
                Collectors.partitioningBy(m->m.getLikes()>20,
                        Collectors.mapping(Movie::getName,
                                Collectors.joining(",")))
        );
        System.out.println(result22);//{false=d,b,a,c, true=}

        //Primitive Type Streams
        IntStream.of(1,2,3);
        DoubleStream.of(1,4.4,23.4);
        LongStream.of(3,6,4,23);
        IntStream.range(1,3).forEach(System.out::println);//1 2

    }
}

以上是关于Java集合框架 流 Streams| Mapping| Filtering| Slicing | Sorting |Reducing | Collectors|...的主要内容,如果未能解决你的问题,请参考以下文章

Java和Node.js实战 MongoDB 4.x 新特性:Change Streams 变化流

java Streams API介绍

反应式流 Reactive Streams 入门介绍

Java 8 Streams API 详解

Kafka Streams与其他流处理平台的差异在哪里?

一篇入门reactive streams背压响应流编程