Java8新特性---Stream流

什么是Stream

  • 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
  • 集合讲究的是数据,流讲的是计算

注意:

  • Stream不会自己存储元素
  • Stream不会改变源对象,相反,他们会返回持有结果的新的Stream
  • Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream操作步骤

请添加图片描述
对于一个数据源,我们先获取一个流,然后对这些流进行处理,包括筛选、切片、映射、排序等,最后还需要一个终止操作,包括查找匹配、找最大、最小值、迭代、计算、规约等。

  • 在这个过程中就,有几点需要注意,首先数据源是没有发生变化的,所做的处理都是对于流,源数据源不变。第二,它是延迟执行的,也就是如果没有终止操作,那么无论做什么中间操作,它都是不做任何处理,没有变化的,只有出现了终止操作,才会进行处理。同时,终止操作也只能有一个,有了终止操作后就不能再对流进行操作。

  • 1、创建Stream
    一个数据源(如:集合、数组),获取一个流

  • 2、中间操作
    一个中间操作链,对数据源的数据进行处理

  • 3、终止操作
    一个终止操作,执行中间操作链,并产生结果

创建Stream流

Java8 中的 Collection 接口被扩展,提供了两个获取流的方法:

  • default Stream stream() : 返回一个顺序流

  • default Stream parallelStream() : 返回一个并行流

由数组创建流

  • static Stream stream(T[] array): 返回一个流
  • 重载形式,能够处理对应基本类型的数组:
    ⚫ public static IntStream stream(int[] array)
    ⚫ public static LongStream stream(long[] array)
    ⚫ public static DoubleStream stream(double[] array)

由值创建流

  • 可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。
  • ⚫ public static Stream of(T… values) : 返回一个流

由函数创建流:创建无限流

  • 可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流。
  • ⚫ 迭代 public static Stream iterate(final T seed, final UnaryOperator f)
  • ⚫ 生成 public static Stream generate(Supplier s)
@Test
    public void test1(){
        //通过Collection 系列集合提供的stream()或parallelStream()
        ArrayList<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
        //通过Arrays中的静态方法stream()获取数组流
        Employee[] employees = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(employees);

        //通过Stream类中的静态方法of()
        Stream<String> stream3 = Stream.of("aa", "bb", "cc");

        //创建无限流
        //迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.limit(22)
                .forEach(System.out::println);

        //生成
        Stream<Double> stream5 = Stream.generate(() -> Math.random());
    }

Stream的中间操作

  • 多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。

筛选与切片

在这里插入图片描述

List<Employee> emps = Arrays.asList(
            new Employee(102, "李四", 59, 6666.66, Employee.Status.BUSY),
            new Employee(101, "张三", 18, 9999.99, Employee.Status.FREE),
            new Employee(103, "王五", 28, 3333.33, Employee.Status.VOCATION),
            new Employee(104, "赵六", 8, 7777.77, Employee.Status.BUSY),
            new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
            new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
            new Employee(105, "田七", 38, 5555.55, Employee.Status.BUSY)
    );
    @Test
    public void test2(){
        Stream<Employee> stream = emps.stream()
                .filter((e) -> {
                    System.out.println("Stream中间操作");
                    return e.getAge() > 35;
                });

        //终止操作
        stream.forEach(System.out::println);
    }

    @Test
    public void test3(){
        emps.stream()
                .filter((e)->e.getSalary()>5000)
                .limit(2)
                .forEach(System.out::println);
    }
    @Test
    public void test4(){
        emps.stream()
                .filter((e)->e.getSalary()>5000)
                .skip(2)
                .distinct()
                .forEach(System.out::println);
    }

映射

在这里插入图片描述

 @Test
    public void test5(){
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

        list.stream()
                .map((str)->str.toUpperCase())
                .forEach(System.out::println);

        System.out.println("--------------------");

        //应用,获取一个集合中的某种属性的集合
        emps.stream()
                .map(Employee::getName)
                .forEach(System.out::println);

        System.out.println("--------------------");


        Stream<Stream<Character>> stream = list.stream()
                .map(StreamTest1::filterCharacter); //{{a,a,a},{b,b,b}...}
        stream.forEach((sm)->{
            sm.forEach(System.out::println);
        });

        System.out.println("--------------------");

        Stream<Character> characterStream = list.stream()
                .flatMap(StreamTest1::filterCharacter);//{a,a,a,b,b,b...}
        characterStream.forEach(System.out::println);
    }

    public static Stream<Character> filterCharacter(String str){
        List<Character> list =new ArrayList<>();
        for(Character ch:str.toCharArray()){
            list.add(ch);
        }
        return list.stream();
    }

排序

在这里插入图片描述

 @Test
    public void test6(){
        List<String> list = Arrays.asList("ccc", "aaa", "bbb", "ddd", "eee");
        list.stream()
                .sorted()
                .forEach(System.out::println);
        System.out.println("--------------------");
        emps.stream()
                .sorted((e1,e2)->{
                    if(e1.getAge()==e2.getAge()){
                        return e1.getId()-e2.getId();
                    }else{
                        return e1.getAge()-e2.getAge();
                    }
                }).forEach(System.out::println);
    }

Stream的终止操作

  • 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。
  • 使用终止操作后,流不能再操作

查找与匹配

在这里插入图片描述

 @Test
    public void test7(){
        boolean b1 = emps.stream()
                .allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(b1);

        boolean b2 = emps.stream()
                .anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(b2);

        boolean b3 = emps.stream()
                .noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(b3);

        Optional<Employee> op1 = emps.stream()
                .sorted(Comparator.comparingDouble(Employee::getSalary))
                .findFirst();
        System.out.println(op1.get());

        Optional<Employee> op2 = emps.stream()
                .filter((e)->e.getStatus().equals(Employee.Status.BUSY))
                .findAny();
        System.out.println(op2.get());

    }

计算、求最值、迭代

在这里插入图片描述

@Test
    public void test8(){
        long count = emps.stream()
                .count();
        System.out.println(count);

        Optional<Employee> optional1 = emps.stream()
                .max(Comparator.comparingDouble(Employee::getSalary));
        System.out.println(optional1.get());

        Optional<Double> optional2 = emps.stream()
                .map(Employee::getSalary)
                .min(Double::compare);
        System.out.println(optional2.get());
    }

归约

在这里插入图片描述

  • map 和 reduce 的连接通常称为map-reduce 模式,因 Google 用它来进行网络搜索而出名。
@Test
    public void test9(){
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer sum = list.stream()
                .reduce(1, (x, y) -> x + y);//从1开始做x+y操作 -> 1+1+2+....+10
        System.out.println(sum);


        System.out.println("----------------------");

        Optional<Double> op = emps.stream()
                .map(Employee::getSalary)
                .reduce(Double::sum);
        System.out.println(op.get());

    }

收集

在这里插入图片描述

  • Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:
    在这里插入图片描述
    在这里插入图片描述
public class StreamTest2 {

    List<Employee> emps = Arrays.asList(
            new Employee(102, "李四", 79, 6666.66, Employee.Status.BUSY),
            new Employee(101, "张三", 18, 9999.99, Employee.Status.FREE),
            new Employee(103, "王五", 28, 3333.33, Employee.Status.VOCATION),
            new Employee(104, "赵六", 8, 7777.77, Employee.Status.BUSY),
            new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
            new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
            new Employee(105, "田七", 38, 5555.55, Employee.Status.BUSY)
    );
    @Test
    public void test3(){
        List<String> list = emps.stream()
                .map(Employee::getName)
                .collect(Collectors.toList());

        list.forEach(System.out::println);

        System.out.println("----------------------------------");

        Set<String> set = emps.stream()
                .map(Employee::getName)
                .collect(Collectors.toSet());

        set.forEach(System.out::println);

        System.out.println("----------------------------------");

        HashSet<String> hs = emps.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new));

        hs.forEach(System.out::println);
    }

    @Test
    public void test4(){
        Optional<Double> max = emps.stream()
                .map(Employee::getSalary)
                .collect(Collectors.maxBy(Double::compare));

        System.out.println(max.get());

        Optional<Employee> op = emps.stream()
                .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

        System.out.println(op.get());

        Double sum = emps.stream()
                .collect(Collectors.summingDouble(Employee::getSalary));

        System.out.println(sum);

        Double avg = emps.stream()
                .collect(Collectors.averagingDouble(Employee::getSalary));

        System.out.println(avg);

        Long count = emps.stream()
                .collect(Collectors.counting());

        System.out.println(count);

        System.out.println("--------------------------------------------");

        DoubleSummaryStatistics dss = emps.stream()
                .collect(Collectors.summarizingDouble(Employee::getSalary));

        System.out.println(dss.getMax());
    }

    //分组
    @Test
    public void test5(){
        Map<Employee.Status, List<Employee>> map = emps.stream()
                .collect(Collectors.groupingBy(Employee::getStatus));

        System.out.println(map);
    }

    //多级分组
    @Test
    public void test6(){
        Map<Employee.Status, Map<String, List<Employee>>> map = emps.stream()
                .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
                    if (e.getAge() >= 60)
                        return "老年";
                    else if (e.getAge() >= 35)
                        return "中年";
                    else
                        return "成年";
                })));

        System.out.println(map);
    }

    //分区
    @Test
    public void test7(){
        Map<Boolean, List<Employee>> map = emps.stream()
                .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));

        System.out.println(map);
    }

    //
    @Test
    public void test8(){
        String str = emps.stream()
                .map(Employee::getName)
                .collect(Collectors.joining("," , "----", "----"));

        System.out.println(str);
    }

    @Test
    public void test9(){
        Optional<Double> sum = emps.stream()
                .map(Employee::getSalary)
                .collect(Collectors.reducing(Double::sum));

        System.out.println(sum.get());
    }
}

并行流和串行流

  • 并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。
  • Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API 可以声明性地通过 parallel()sequential() 在并行流与顺序流之间进行切换。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

&*Savior

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值