Java强大的Stream API

167 阅读10分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第16天,点击查看活动详情

Stream API说明

Java8中有两大最为重要的改变。第一个是Lambda 表达式;另外一个则是 Stream API

Stream API ( java.util.stream) 把真正的函数式编程风格引入到Java中。这 是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

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

为什么要使用Stream API

实际开发中,项目中多数数据源都来自于Mysql,Oracle等。但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQL的数据就需要 Java层面去处理。

Stream 和 Collection 集合的区别:Collection 是一种静态的内存数据 结构,而 Stream 是有关计算的。前者是主要面向内存,存储在内存中, 后者主要是面向 CPU,通过 CPU 实现计算

但在当今这个数据大爆炸的时代,在数据来源多样化、数据海量化的今天,很多时候不得不脱离 RDBMS,或者以底层返回的数据为基础进行更上层的数据统计。而 Java 的集合 API 中,仅仅有极少量的辅助型方法,更多的时候是程序员需要用 Iterator 来遍历集合,完成相关的聚合应用逻辑。这是一种远不够高效、笨拙的方法。在 Java 7 中,如果要发现 type 为 grocery 的所有交易,然后返回以交易值降序排序好的交易 ID 集合,我们需要这样写:

List<Transaction> groceryTransactions = new Arraylist<>();
for(Transaction t: transactions){
 if(t.getType() == Transaction.GROCERY){
 groceryTransactions.add(t);
 }
}
Collections.sort(groceryTransactions, new Comparator(){
 public int compare(Transaction t1, Transaction t2){
 return t2.getValue().compareTo(t1.getValue());
 }
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions){
 transactionsIds.add(t.getId());
}

而在 Java 8 使用 Stream,代码更加简洁易读;而且使用并发模式,程序执行速度更快。

List<Integer> transactionsIds = transactions.parallelStream().
 filter(t -> t.getType() == Transaction.GROCERY).
 sorted(comparing(Transaction::getValue).reversed()).
 map(Transaction::getId).
 collect(toList());

什么是 Stream

Stream到底是什么呢? 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。

“集合讲的是数据,Stream讲的是计算!”

注意:

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

Stream的操作三个步骤

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

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

  3. 终止操作(终端操作) 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用

image-20201223161806766

创建Stream

首先创建一个EmployeeEmployeeData

public class Employee {
    private int id;
    private String name;
    private int age;
    private double salary;


    public Employee() {
    }

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Employee(int id) {
        this.id = id;
    }

    public Employee(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id && age == employee.age && Double.compare(employee.salary, salary) == 0 && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, salary);
    }
}
/**
 * 提供用于测试的数据
 */
public class EmployeeData {

    public static List<Employee> getEmployees() {
        List<Employee> list = new ArrayList<>();

        list.add(new Employee(1001, "马化腾", 34, 6000.38));
        list.add(new Employee(1002, "马云", 12, 9876.12));
        list.add(new Employee(1003, "刘强东", 33, 3000.82));
        list.add(new Employee(1004, "雷军", 26, 7657.37));
        list.add(new Employee(1005, "李彦宏", 65, 5555.32));
        list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
        list.add(new Employee(1007, "任正非", 26, 4333.32));
        list.add(new Employee(1008, "扎克伯格", 35, 2500.32));

        return list;
    }

}

通过集合

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

  • default Stream<E> stream() : 返回一个顺序流
  • default Stream<E> parallelStream() : 返回一个并行流

image-20201223163836625

//创建Steam方式一:通过集合
@Test
public void test1() {
    List<Employee> employees = EmployeeData.getEmployees();
    //default Stream<E> stream():返回一个顺序流
    Stream<Employee> stream = employees.stream();
    //default Stream<E> parallelStream():返回一个并行流,并行操作。顺序不保证
    Stream<Employee> parallelStream = employees.parallelStream();
}

通过数组

Java8 中的 Arrays 的静态方法 stream() 可以获取数组流: static <T> Stream<T> stream(T[] array): 返回一个流

重载形式,能够处理对应基本类型的数组:

  • public static IntStream stream(int[] array)
  • public static LongStream stream(long[] array)
  • public static DoubleStream stream(double[] array)

image-20201223164056077

//创建Steam方式二:通过数组
@Test
public void test2() {
    int[] arr = {1, 2, 3, 4, 5, 6};
    //调用Arrays类的public static <T> Stream<T> stream(T[] array) 返回一个流
    IntStream stream = Arrays.stream(arr);

    Employee e1 = new Employee(1001, "Tom");
    Employee e2 = new Employee(1001, "Jerry");
    Employee[] arr1 = {e1, e2};
    Stream<Employee> stream1 = Arrays.stream(arr1);
}

通过Stream的of()

可以调用Stream类静态方法 of(), 通过显示值创建一个 流。它可以接收任意数量的参数。

  • public static<T> Stream<T> of(T... values) : 返回一个流

image-20201223164227424

//创建Stream方式三:通过Stream的of()
@Test
public void test3() {
    Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
}

创建无限流

可以使用静态方法 Stream.iterate() 和 Stream.generate(), 创建无限流。

  • 迭代 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
  • 生成 public static<T> Stream<T> generate(Supplier<T> s)

image-20201223164641197

//创建 Stream方式四:创建无限流
@Test
public void test4() {

    //迭代
    //public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
    //遍历前10个偶数
    Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);

    //生成
    //public static<T> Stream<T> generate(Supplier<T> s)
    Stream.generate(Math::random).limit(10).forEach(System.out::println);
}

image-20201223164721180

这里使用了后面会讲的其他Stream API操作。

Stream的中间操作

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

筛选与切片

image-20201223165522877

方法描述
filter(Predicate p)接收 Lambda , 从流中排除某些元素
distinct()筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
limit(long maxSize)截断流,使其元素不超过给定数量
skip(long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一 个空流。与 limit(n) 互补

image-20201223170218083

//1-筛选与切片
@Test
public void test1() {
    List<Employee> list = EmployeeData.getEmployees();
    //filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
    Stream<Employee> stream = list.stream();
    //练习:查询员工表中薪资大于7000的员工信息
    stream.filter(employee -> employee.getSalary() > 7000).forEach(System.out::println);

    System.out.println();
    //limit(n)——截断流,使其元素不超过给定数量。
    list.stream().limit(3).forEach(System.out::println);

    System.out.println();
    //skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
    list.stream().skip(3).forEach(System.out::println);

    System.out.println();
    //distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    list.add(new Employee(1010, "刘强东", 40, 8000));
    list.add(new Employee(1010, "刘强东", 41, 8000));
    list.add(new Employee(1010, "刘强东", 40, 8000));
    list.add(new Employee(1010, "刘强东", 40, 8000));
    list.add(new Employee(1010, "刘强东", 40, 8000));
    System.out.println(list);
    System.out.println();

    list.stream().distinct().forEach(System.out::println);
}

image-20201223170313157

映射

image-20201223170355480

方法描述
map(Function f)接收一个函数作为参数,该函数会被应用到每个元 素上,并将其映射成一个新的元素。
mapToDouble(ToDoubleFunction f)接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f)接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 LongStream。
flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另 一个流,然后把所有流连接成一个流

image-20201223172413660

//映射
@Test
public void test2() {
    //map(Function f)——--->接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。
    List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
    list.stream().map(new Function<String, String>() {

        @Override
        public String apply(String s) {
            return s.toUpperCase();
        }
    }).forEach(System.out::println);


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


    ////练习1:获取员工姓名长度大于3的员工的姓名。
    List<Employee> employees = EmployeeData.getEmployees();
    employees.stream().map(employee -> employee.getName()).filter(name -> name.length() > 3).forEach(System.out::println);
    System.out.println();

}

image-20201223172505470

flatMap

img

img

image-20201224111417560

@Test
public void test3(){
    //练习2:
    //Function<T, R>:R                  apply(T t);
    //              :Stream<Character>  fromStringToStream(String s)

    List<String> list = Arrays.asList("aa", "bb", "cc", "dd");

    //Stream<Stream<Character>> stream = list.stream().map(s -> fromStringToStream(s));
    Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);

    streamStream.forEach(s -> {
        s.forEach(System.out::println);
    });
    System.out.println();

    //flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
    Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
    characterStream.forEach(System.out::println);

}

//将字符串中的多个字符构成的集合转换为对应的Stream的实例
public static Stream<Character> fromStringToStream(String str) {//aa
    ArrayList<Character> list = new ArrayList<>();
    //将str变成Char[]数组,依次遍历添加到list中。
    for (Character c : str.toCharArray()) {
        list.add(c);//a,a
    }
    return list.stream();
}

image-20201224111741283

排序

image-20201224111907734

方法描述
sorted()产生一个新流,其中按自然顺序排序
Sorted(Comparator com)产生一个新流,其中按比较器顺序排序

image-20201224112214548

@Test
public void test5() {
    //sorted()——自然排序
    List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);
    list.stream().sorted().forEach(System.out::println);
    //抛异常,原因:Employee没有实现Comparable接口
    //List<Employee> employees = EmployeeData.getEmployees();
    //employees.stream().sorted().forEach(System.out::println);


    //sorted(Comparator com)——定制排序

    List<Employee> employees = EmployeeData.getEmployees();
    employees.stream().sorted((e1, e2) -> {
        //年龄排序
        int ageValue = Integer.compare(e1.getAge(), e2.getAge());
        if (ageValue != 0) {
            return ageValue;
        } else {
            return -Double.compare(e1.getSalary(), e2.getSalary());
        }

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

image-20201224112325830

终止操作

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

匹配与查找

image-20201224112547700

方法描述
allMatch(Predicate p)检查是否匹配所有元素
anyMatch(Predicate p)检查是否至少匹配一个元素
noneMatch(Predicate p)检查是否没有匹配所有元素
findFirst()返回第一个元素
findAny()返回当前流中的任意元素

image-20201224112823507

//1-匹配与查找
@Test
public void test1() {
    List<Employee> employees = EmployeeData.getEmployees();
    //allMatch(Predicate p)——检查是否匹配所有元素。
    //  练习:是否所有的员工的年龄都大于18
    System.out.println(employees.stream().allMatch(employee -> employee.getAge() > 18));

    //anyMatch(Predicate p)——检查是否至少匹配一个元素。
    // 练习:是否存在员工的工资大于 10000
    System.out.println(employees.stream().anyMatch(employee -> employee.getSalary() > 10000));

    //noneMatch(Predicate p)——检查是否没有匹配的元素。
    //   练习:是否存在员工姓“雷”
    System.out.println(employees.stream().noneMatch(employee -> employee.getName().startsWith("雷")));

    //findFirst——返回第一个元素
    Optional<Employee> employee = employees.stream().findFirst();
    System.out.println(employee);
    //findAny——返回当前流中的任意元素
    Optional<Employee> employee1 = employees.parallelStream().findAny();
    System.out.println(employee1);

}

image-20201224112938333

image-20201224114305591

方法描述
count()返回流中元素总数
max(Comparator c)返回流中最大值
min(Comparator c)返回流中最小值
forEach(Consumer c)内部迭代(使用 Collection 接口需要用户去做迭代 称为外部迭代。相反,Stream API 使用内部迭 代——它帮你把迭代做了)

image-20201224114839122

@Test
public void test2() {
    List<Employee> employees = EmployeeData.getEmployees();
    // count——返回流中元素的总个数
    long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
    System.out.println(count);

    //max(Comparator c)——返回流中最大值
    //练习:返回最高的工资:
    Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
    Optional<Double> maxSalary = salaryStream.max(Double::compare);
    System.out.println(maxSalary);

    //min(Comparator c)——返回流中最小值
    //练习:返回最低工资的员工
    Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
    System.out.println(employee);
    System.out.println();
    //forEach(Consumer c)——内部迭代
    employees.stream().forEach(System.out::println);

    //使用集合的遍历操作
    employees.forEach(System.out::println);
}

image-20201224115003442

归约

image-20201224115130556

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

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

image-20201224115657791

//2-归约
@Test
public void test3() {
    //reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
    //练习1:计算1-10的自然数的和
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    Integer sum = list.stream().reduce(0, Integer::sum);
    System.out.println(sum);

    //reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
    //练习2:计算公司所有员工工资的总和
    List<Employee> employees = EmployeeData.getEmployees();
    Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
    //Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
    Optional<Double> sumMoney = salaryStream.reduce((d1, d2) -> d1 + d2);
    System.out.println(sumMoney.get());

}

image-20201224125409801

收集

image-20201224125553593

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

Collector 接口中方法的实现决定了如何对流执行收集的操作(如收集到 List、Set、 Map)。

另外, Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例, 具体方法与实例如下表:

image-20201224125737423

image-20201224125752696

image-20201224125819140

    //3-收集
    @Test
    public void test4() {
        //collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
        //练习1:查找工资大于6000的员工,结果返回为一个List或Set
        List<Employee> employees = EmployeeData.getEmployees();
        //List
        List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
        employeeList.forEach(System.out::println);

        System.out.println();

        //Set
        Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
        employeeSet.forEach(System.out::println);

    }

}

image-20201224125844332