zoukankan      html  css  js  c++  java
  • Java 8 Stream API

    Java 8 Stream API

    JDK8 中有两大最为重要的改变。第一个是 Lambda 式;另外 Stream API(java.util.stream.*)

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

    1. 什么是 Stream

    流(Stream)到底是什么呢?

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

    注意:

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

    2. Stream 的操作三个步骤

    1. 创建 Stream :一个数据源(如:集合、数组),获取一个流
    2. 中间操作 :一个中间操作链,对数据源的数据进行处理
    3. 终止操作(终端操作) :一个终止操作,执行中间操作链,并产生结果

    2.1 创建 Stream 的 4 种方法

    //1. Collection 提供了两个方法  stream() 与 parallelStream()
    List<String> list = new ArrayList<>();
    Stream<String> stream = list.stream(); //获取一个顺序流
    Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
    
    //2. 通过 Arrays 中的 stream() 获取一个数组流
    Integer[] nums = new Integer[10];
    Stream<Integer> stream1 = Arrays.stream(nums);
    
    //3. 通过 Stream 类中静态方法 of()
    Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
    
    //4. 创建无限流
    //迭代
    Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
    stream3.forEach(System.out::println);
    
    //生成
    Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
    stream4.forEach(System.out::println);
    

    2.2 Stream 的中间操作

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

    2.2.1 筛选和切片

    方法 描述
    filter(Predicate p) 接收 Lambda ,从流中排除某些元素
    limit(long maxSize) 截断流,使其元素不超过给定数量
    skip(long n)() 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
    distinct() 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    public class Employee {
    
        private int id;
        private String name;
        private int age;
        private double salary;
        private Status status;
    
        // 省略 getter/setter/equals/hash
    
        public enum Status {
            FREE, BUSY, VOCATION;
        }
    }
    // 造点数据
    List<Employee> emps = Arrays.asList(
            new Employee(102, "李四", 59, 6666.66, Status.BUSY),
            new Employee(101, "张三", 18, 9999.99, Status.FREE),
            new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
            new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
            new Employee(104, "赵六", 8, 7777.77, Status.FREE),
            new Employee(104, "赵六", 8, 7777.77, Status.FREE),
            new Employee(105, "田七", 38, 5555.55, Status.BUSY)
    );
    
    //所有的中间操作不会做任何的处理
    Stream<Employee> stream = emps.stream()
        .filter((e) -> {
            System.out.println("测试中间操作");
            return e.getAge() <= 35;
        });
    
    //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
    stream.forEach(System.out::println);
    

    2.2.2 映射

    方法 描述
    map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
    mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 Doub1eStream
    mapToInt(ToIntFunction f) 同上
    mapToLong(ToLongFunction f) 同上
    flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
    Stream<String> stringStream = emps.stream()
            .map((e) -> e.getName());
    stringStream.forEach(System.out::println);
    
    System.out.println("-------------------------------------------");
    List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
    strList.stream()
            .map(String::toUpperCase)
            .forEach(System.out::println);
    
    System.out.println("-------------------map------------------------");
    Stream<Stream<Character>> stream2 = strList.stream()
           .map(StreamAPITest1::filterCharacter);
    stream2.forEach((sm) -> {
        sm.forEach(System.out::println);
    });
    
    System.out.println("-----------------------flatMap----------------------");
    Stream<Character> stream3 = strList.stream()
           .flatMap(StreamAPITest1::filterCharacter);
    stream3.forEach(System.out::println);
    

    2.2.3 排序

    方法 描述
    sorted() 产生一个新流,其中按自然顺序排序
    sorted(Comparator c) 产生一个新流,其中按比较器顺序排序
    emps.stream()
        .map(Employee::getName)
        .sorted()
        .forEach(System.out::println);
    
    System.out.println("------------------------------------");
    
    emps.stream()
        .sorted((x, y) -> {
            if(x.getAge() == y.getAge()){
                return x.getName().compareTo(y.getName());
            }else{
                return Integer.compare(x.getAge(), y.getAge());
            }
        }).forEach(System.out::println);
    

    2.3 Stream 的终止操作

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

    2.3.1 查找与匹配

    方法 描述
    allMatch(Predicate p) 检查是否匹配所有元素
    anyMatch(Predicate p) 检查是否至少匹配一个元素
    findFirst() 检查是否没有匹配所有元素返回第一个元素
    findAny() 返回当前流中的任意元素
    count() 返回流中元素总数
    max(Comparator c) 返回流中最大值
    max(Comparator c) 返回流中最小值
    forEach() 内部迭代
    @Test
    public void test1(){
        boolean bl1 = emps.stream().allMatch((e) -> e.getStatus().equals(Status.BUSY));
        boolean bl2 = emps.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY));
        boolean bl3 = emps.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY));
    }
    
    @Test
    public void test2(){
        Optional<Employee> op1 = emps.stream()
                .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
                .findFirst();
        Optional<Employee> op2 = emps.parallelStream()
                .filter((e) -> e.getStatus().equals(Status.FREE))
                .findAny();
    }
    
    @Test
    public void test3(){
        long count = emps.stream()
                         .filter((e) -> e.getStatus().equals(Status.FREE))
                         .count();   
        System.out.println(count);
        
        Optional<Double> op = emps.stream()
            .map(Employee::getSalary)
            .max(Double::compare);    
        System.out.println(op.get());
        
        Optional<Employee> op2 = emps.stream()
            .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(op2.get());
    }
    
    //注意:流进行了终止操作后,不能再次使用
    @Test
    public void test4(){
        Stream<Employee> stream = emps.stream()
         .filter((e) -> e.getStatus().equals(Status.FREE));
        long count = stream.count();
        
        stream.map(Employee::getSalary)
            .max(Double::compare);
    }
    

    2.3.2 归约

    方法 描述
    reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回T
    reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional

    备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。

    @Test
    public void test1(){
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        
        Integer sum = list.stream()
            .reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        
        Optional<Double> op = emps.stream()
            .map(Employee::getSalary)
            .reduce(Double::sum);    
        System.out.println(op.get());
    }
    
    //需求:搜索名字中 “六” 出现的次数
    @Test
    public void test2(){
        Optional<Integer> sum = emps.stream()
            .map(Employee::getName)
            .flatMap(StreamAPITest1::filterCharacter)
            .map((ch) -> {
                if(ch.equals('六'))
                    return 1;
                else 
                    return 0;
            }).reduce(Integer::sum);
        System.out.println(sum.get());
    }
    

    2.3.3 收集

    方法 描述
    collect(Collector c) 将流转换为其他形式。接收一个 Collector 接口的实现,用于给 Stream 中元素做汇总的方法

    Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set/Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:

    方法 返回类型 作用
    toList List 把流中元素收集到 List
    toSet Set 把流中元素收集到 Set
    toCollection Collection 把流中元素收集到 Collection
    counting Long 计算流中元素的个数
    summingInt Integer 对流中元素的整数属性求和
    averagingInt Double 计算流中元素Integer属性的平均值
    summarizingInt IntSummaryStatistics 收集流中Integer属性的统计值,如:平均值
    joining String 连接流中每个字符串
    maxBy Optional 根据比较器选择最大值
    minBy Optional 根据比较器选择最小值
    reducing 归约产生的类型 收集流中Integer属性的统计值,如:平均值
    collectingAndThen 转换函数返回的类型 包裹另一个收集器,对其结果转换函数
    groupingBy Map<K, List> 根据某属性值对流分组,属性为K,结果为V
    partitioningBy Map<Boolean, List> 根据true或false进行分区

    Map<Boolean, List> vd = list.stream().collect(Collectors.partitioningBy(Employee::getManage));

    //collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
    @Test
    public void test1(){
        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 test2(){
        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);
        
        DoubleSummaryStatistics dss = emps.stream()
            .collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println(dss.getMax());
    }
    
    //分组
    @Test
    public void test3(){
        Map<Status, List<Employee>> map = emps.stream()
            .collect(Collectors.groupingBy(Employee::getStatus));
        System.out.println(map);
    }
    
    //多级分组
    @Test
    public void test4(){
        Map<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 test5(){
        Map<Boolean, List<Employee>> map = emps.stream()
            .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));    
        System.out.println(map);
    }
    
    //
    @Test
    public void test6(){
        String str = emps.stream()
            .map(Employee::getName)
            .collect(Collectors.joining("," , "----", "----"));    
        System.out.println(str);
    }
    
    @Test
    public void test7(){
        Optional<Double> sum = emps.stream()
            .map(Employee::getSalary)
            .collect(Collectors.reducing(Double::sum));    
        System.out.println(sum.get());
    }
    

    Java 8 新特性

    1. Java 8 Lambda 表达式
    2. Java 8 Stream API
    3. Java 8 Optional 类深度解析
    4. Java 8 新时间日期 API
    5. Java 8 接口中的默认方法与静态方法
    6. Java 8 可重复注解与类型注解
  • 相关阅读:
    java8关于list的操作
    jdk8的.toMap()
    Mybatis中报错org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题解决
    springboot集成bootstrap遇到的问题
    java文件下载
    idea中mybatis自动生成代码方式
    文件读写操作inputStream转为byte[] , 将InputStream写入本地文件
    Polar transformer networks
    Fine-Grained Person Re-identification
    Person Re-identification by Contour Sketch under Moderate Clothing Change
  • 原文地址:https://www.cnblogs.com/binarylei/p/8604286.html
Copyright © 2011-2022 走看看