0
点赞
收藏
分享

微信扫一扫

JAVA8新特性--Stream

七千22 2022-03-11 阅读 43

Stream流,提供了很多方法对一个集合等数据的处理,得到想要的数据,是一个操作数据的工具类

将集合对象转换成流对象遍历

List<String> list = Arrays.asList("数据1","数据2","数据3");
list.stream().forEach(System.out :: println );

流的定义: 从支持流操作的数据源生成元素序列

元素序列: 集合是用来储存元素, 流也提供了接口,可以访问特定的元素类型,流访问数据更多的是对数据的处理

源: 为流提供数据的源,如集合,数组,输入或输出资源,流对这个数据生成流时,也会保留原有数据的顺序

数据处理操作: 对数据的一些操作,如filter map reduce find match sort等,可以顺序执行,也可以并发执行

Stream流对象的创建几种常用方式

Collection接口中的方法stream()顺序流对象, parallelStream()并行流对象: 所有这个接口的实现类都可以通过这种方式创建流对象

List<Integer> list = Arrays.asList(1,2,34,4);
Stream<Integer> stream = list.stream();

Arrays.stream() : 数组工具类中的创建流对象静态方法,根据传入的数组创建一个流对象

Integer[] arr = {1,2,3,5};
Stream<Integer> stream = Arrays.stream(arr);

Stream.of() : Stream类中的静态方法,根据传入的多个元素创建一个流对象

Stream<String> stream2 = Stream.of("q", "w", "e");

Stream.iterate() : Stream类中的静态方法,指定一个参数,定义一个匿名实现类实现UnaryOperator接口,这个接口是函数型接口的子接口,将第一个参数传入,在实现方法中可以对这个参数进行一些运算或处理,再返回再重新传入,类似于循环,所以在后面需要调用limit方法指定限制多少次这样的操作,最终得到这些值形成的一个流对象

Stream<Integer> iterate = Stream.iterate(1, s -> s + 1).limit(5);

Stream.generate() : Stream类中的静态方法,生成无限流,放入一个匿名实现类,实现供给型接口Supplier,在方法中写出要返回什么东西,循环返回,所以也要再调用limit方法限制返回的个数,最终得到这些值形成的流对象

Stream.generate(() -> new Random().nextInt(5)).limit(5).forEach(System.out :: println);

Stream流中提供的一些实例方法

        //filter() : 根据传入的断言型接口匿名实现类方法中的判断规则过滤流中的元素
        Arrays.asList("数据1", "数据2", "数据3").stream().filter(s -> s.endsWith("3")).forEach(System.out::println);
        System.out.println("===========================");
        //distinct():去重,根据流中数据的 hashCode和 equals去除重复元素,所以想要去重,流中的元素一定要实现这两个方法
        Stream.of(new Product("手机",6000),new Product("手机",6000)).distinct().forEach(System.out::println);
        System.out.println("===========================");
        //limit(long n):限定保留n个数据
        Stream.of("q","w","e","r").limit(2).forEach(System.out :: println);
        System.out.println("===========================");
        //skip(long n):跳过n个数据
        Stream.of("q","w","e","r").skip(2).forEach(System.out :: println);

映射

        //map(Function<T, R> f):流中的每一个元素都会被传入到函数型接口匿名实现类中的方法进行处理再返回到流中
        Stream.of("q","w","e","r").map(s -> s.toUpperCase()).forEach(System.out :: println);
        System.out.println("===========================");
        //flatMap(Function<T, Stream<R>> mapper):将流中的每个元素传入到函数型接口匿名实现类的方法中,将流中的每个元素都转换成另一个流,然后把所有流连接成一个流
        Stream<List<Integer>> stream3 = Stream.of(Arrays.asList(1,2,3),Arrays.asList(4,5,6));
        stream3.flatMap(List::stream).forEach(System.out :: println);

排序

        //sorted():自然排序使用Comparable<T>的int compareTo(T o)方法,所以流中的元素必须实现该方法
        Stream.of(3,3,265,3,26,57,7,3,9).sorted().forEach( s -> System.out.print(s+"  "));
        System.out.println("===========================");
        //sorted(Comparator<T> com):定制排序使用Comparator的int compare(T o1, T o2)方法 (一个Comparator的匿名实现类,实现这个方法)
        Stream.of(3,3,265,3,26,57,7,3,9).sorted((o1,o2)-> o1-o2).forEach( s -> System.out.print(s+"  "));

查找匹配

        //allMatch:检查所有元素是否符合这个断言型接口匿名实现类判断规则,全部符合返回true
        System.out.println(Stream.of(23, 3, 5, 6, 7, 3, 3).allMatch(s -> s >= 3));
        System.out.println("===========================");
        //anyMatch:检查是否至少一个元素符合这个断言型接口匿名实现类的判断规则
        System.out.println(Stream.of(3, 6, 23, 3).anyMatch(s -> s == 3));
        System.out.println("===========================");
        //noneMatch:检查所有元素是否符合这个断言型接口匿名实现类中的判断规则,如果都不符合,返回true
        System.out.println(Stream.of(4, 62, 6, 2).noneMatch(s -> s > 62));
        System.out.println("===========================");
        //findFirst:返回流中第一个元素(返回值装在Optional<T>类型对象中,可以通过这个类型对象的get方法获得其中的值)
        Optional<Integer> first = Stream.of(3, 6, 3, 7, 9).findFirst();
        Integer integer = first.get();
        System.out.println("===========================");
        //findAny:返回当前流中的任意元素(返回值装在Optional<T>类型对象中,可以通过这个类型对象的get方法获得其中的值,一般用于并行流)实验并没有随机
        System.out.println(Stream.of(0,1,2,3,4,5,6,7,8,9).parallel().findAny().get());

Optional是java8新出的容器,这个容器只存1个或0个元素,它用于防止出现NullpointException,它提供如下方法:
•isPresent() : 判断容器中是否有值。
•T get() :获取容器中的元素,若容器为空则抛出NoSuchElement异常。

统计

        //count():返回流中元素的总个数
        long count = Stream.of(1, 2, 3).count();
        System.out.println(count);
        System.out.println("===========================");
        //max(Comparator<T>):返回流中最大值,通过一个比较器的匿名实现类,实现比较规则排序后取最后一位
        System.out.println(Stream.of(2, 35, 5, 7, 4).max((o1, o2) -> o1 - o2).get());
        System.out.println("===========================");
        //min(Comparator<T>):返回流中最小值,通过一个比较器的匿名实现类,实现比较规则排序后取第一位
        System.out.println(Stream.of(2, 35, 5, 7, 4).min((o1, o2) -> o1 - o2).get());
        System.out.println("===========================");

汇总

        //collect()横空出世!
        //collect(Collector<T, A, R>):将流转换为其他形式。
        //collect:将流转换为其他形式:list
        List<Integer> list = Stream.of(1, 1, 2, 2, 3, 4, 5).collect(Collectors.toList());
        System.out.println(list);
        //collect:将流转换为其他形式:set
        Set<Integer> set = Stream.of(1, 1, 2, 2, 3, 4, 5).collect(Collectors.toSet());
        System.out.println(set);
        //collect:将流转换为其他形式:TreeSet
        TreeSet<Integer> treeSet = Stream.of(1, 1, 2, 2, 3, 5,4).collect(Collectors.toCollection(() -> new TreeSet<>()));
        System.out.println(treeSet);
        //collect:将流转换为其他形式:map
        Map<Integer, Integer> map = Stream.of(1, 1, 2, 2, 3, 5, 4).distinct().collect(Collectors.toMap(key -> key, value -> value));
        System.out.println(map);
        //collect:将流转换为其他形式:sum
        Integer sum = Stream.of(1, 1, 2, 2, 3, 5, 4).collect(Collectors.summingInt(v -> v));
        System.out.println(sum);
        IntSummaryStatistics sum2 = Stream.of(1, 1, 2, 2, 3, 5, 4).collect(Collectors.summarizingInt(value -> value));
        long sum1 = sum2.getSum();
        System.out.println(sum1);
        //collect:将流转换为其他形式:avg
        Double avg = Stream.of(1, 1, 2, 2, 3, 5, 4).collect(Collectors.averagingDouble(value -> value));
        System.out.println(avg);
        //collect:将流转换为其他形式:max
        Integer integer = Stream.of(1, 1, 2, 2, 3, 5, 4).collect(Collectors.maxBy((o1, o2) -> o1 - o2)).get();
        System.out.println(integer);
        //collect:将流转换为其他形式:min
        Integer integer1 = Stream.of(1, 1, 2, 2, 3, 5, 4).collect(Collectors.minBy((o1, o2) -> o1 - o2)).get();
        System.out.println(integer1);

分组和分区

//Collectors.groupingBy()对元素做group操作。分组--根据条件分成多个组
        Product product = new Product("手机", 100);
        Product product1 = new Product("手机", 200);
        Product product2 = new Product("电脑", 300);
        Product product3 = new Product("手机", 400);
        Product product4 = new Product("电脑", 500);
        Product product5 = new Product("手机", 600);
        Map<String, List<Product>> map2 = Stream.of(product, product1, product2, product3, product4, product5).collect(Collectors.groupingBy(s -> s.getName()));
        System.out.println(map2);
        //Collectors.partitioningBy()对元素进行二分区操作。分区--根据boolean条件分成两个区
        Map<Boolean, List<Product>> map3 = Stream.of(product, product1, product2, product3, product4, product5).collect(Collectors.partitioningBy(s -> s.getPrice() > 300));
        System.out.println(map3);

顺序流与并行流

数据转换成流的时候使用: steam() 顺序流 parallelStream() 并行流
对一个流对象进行转换时使用 : sequential()转换为顺序流 parallel() 转换为并行流
数据太大时对并行流有一定性能影响

举报

相关推荐

0 条评论