特点

首先,Stream流有一些特性:

  1. Stream流不是一种数据结构,不保存数据,它只是在原数据集上定义了一组操作。
  2. 这些操作是惰性的,即每当访问到流中的一个元素,才会在此元素上执行这一系列操作。
  3. Stream不保存数据,故每个Stream流只能使用一次。

准备三个不同的Bean。

  1. public class Student {
  2. private int id;
  3. private String name;
  4. private String sex;
  5. private Optional<Job> job;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public String getSex() {
  19. return sex;
  20. }
  21. public void setSex(String sex) {
  22. this.sex = sex;
  23. }
  24. public Optional<Job> getJob() {
  25. return job;
  26. }
  27. public void setJob(Optional<Job> job) {
  28. this.job = job;
  29. }
  30. public Student(int id, String name, String sex) {
  31. this.id = id;
  32. this.name = name;
  33. this.sex = sex;
  34. }
  35. public Student() {
  36. }
  37. public Student(int id, String name, String sex, Optional<Job> job) {
  38. super();
  39. this.id = id;
  40. this.name = name;
  41. this.sex = sex;
  42. this.job = job;
  43. }
  44. @Override
  45. public String toString() {
  46. return "Student{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + '}';
  47. }
  48. }
  1. public class Job {
  2. private Optional<Company> company;
  3. public Optional<Company> getCompany() {
  4. return company;
  5. }
  6. public void setCompany(Optional<Company> company) {
  7. this.company = company;
  8. }
  9. public Job(Optional<Company> company) {
  10. super();
  11. this.company = company;
  12. }
  13. }
  1. public class Company {
  2. private String name;
  3. private int id;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. public Company(String name) {
  11. super();
  12. this.name = name;
  13. }
  14. public Company() {
  15. super();
  16. }
  17. public int getId() {
  18. return id;
  19. }
  20. public void setId(int id) {
  21. this.id = id;
  22. }
  23. }

filter方法 (筛选)

  1. List<Student> students = new ArrayList<>();
  2. students.add(new Student(1, "张三", "男"));
  3. students.add(new Student(2, "李四", "女"));
  4. students.add(new Student(3, "王五", "男"));
  5. students.add(new Student(3, "王七", "女"));
  6. students.add(new Student(3, "王七", "女"));
  7. List<String> result = students.stream() // 流
  8. .filter(s -> s.getId() >= 3) // 筛选
  9. .sorted(Comparator.comparing(Student::getId)) // 排序
  10. .map(Student::getName) // 获取(映射)
  11. .distinct() // 去重
  12. .collect(Collectors.toList());// 转换
  13. System.out.println(result);

结果

  1. [王五, 王七]

补充(Stream详细用法大全)

一、概述

Java 8 是一个非常成功的版本,这个版本新增的Stream,配合同版本出现的Lambda ,给我们操作集合(Collection)提供了极大的便利。Stream流是JDK8新增的成员,允许以声明性方式处理数据集合,可以把Stream流看作是遍历数据集合的一个高级迭代器。Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找/筛选/过滤、排序、聚合和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

1、使用流的好处

代码以声明性方式书写,说明想要完成什么,而不是说明如何完成一个操作。
可以把几个基础操作连接起来,来表达复杂的数据处理的流水线,同时保持代码清晰可读。

2、流是什么?

从支持数据处理操作的源生成元素序列.数据源可以是集合,数组或IO资源。
从操作角度来看,流与集合是不同的. 流不存储数据值; 流的目的是处理数据,它是关于算法与计算的。
如果把集合作为流的数据源,创建流时不会导致数据流动; 如果流的终止操作需要值时,流会从集合中获取值; 流只使用一次。
image.png
Stream可以由数组或集合创建,对流的操作分为两种:
中间操作,每次返回一个新的流,可以有多个。
终端操作,每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。
特性:
不是数据结构,不会保存数据。
不会修改原来的数据源,它会将操作后的数据保存到另外一个对象中。(保留意见:毕竟peek方法可以修改流中元素)
惰性求值,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算。

二、分类

image.png

  1. 无状态:指元素的处理不受之前元素的影响;
  2. 有状态:指该操作只有拿到所有元素之后才能继续下去。
  3. 非短路操作:指必须处理所有元素才能得到最终结果;
  4. 短路操作:指遇到某些符合条件的元素就可以得到最终结果,如 A || B,只要A为true,则无需判断B的结果。

    三、Stream的创建

    Stream可以通过集合数组创建。
    1、通过 java.util.Collection.stream() 方法用集合创建流
    1. List<String> list = Arrays.asList("a", "b", "c");
    2. // 创建一个顺序流
    3. Stream<String> stream = list.stream();
    4. // 创建一个并行流
    5. Stream<String> parallelStream = list.parallelStream();
    2、使用 java.util.Arrays.stream(T[]array)方法用数组创建流
    1. int[] array={1,3,5,6,8};
    2. IntStream stream = Arrays.stream(array);
    3、使用 Stream的静态方法:of()、iterate()、generate() ```java Stream stream = Stream.of(1, 2, 3, 4, 5, 6);

Stream stream2 = Stream.iterate(0, (x) -> x + 3).limit(4); stream2.forEach(System.out::println);

Stream stream3 = Stream.generate(Math::random).limit(3); stream3.forEach(System.out::println);

  1. 输出结果:
  2. ```java
  3. 0 3 6 9
  4. 0.6796156909271994
  5. 0.1914314208854283
  6. 0.8116932592396652

stream和 parallelStream的简单区分:stream是顺序流,由主线程按顺序对流执行操作,而 parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。例如筛选集合中的奇数,两者的处理不同之处:
image.png
如果流中的数据量足够大,并行流可以加快处速度。
除了直接创建并行流,还可以通过 parallel()把顺序流转换成并行流:
Optional<Integer> findFirst = list.stream().parallel().filter(x->x>6).findFirst();

四、Stream API简介


image.png
image.png :::info 先贴上几个案例,水平高超的同学可以挑战一下:

从员工集合中筛选出salary大于8000的员工,并放置到新的集合里。

统计员工的最高薪资、平均薪资、薪资之和。

将员工按薪资从高到低排序,同样薪资者年龄小者在前。

将员工按性别分类,将员工按性别和地区分类,将员工按薪资是否高于8000分为两部分。

用传统的迭代处理也不是很难,但代码就显得冗余了,跟Stream相比高下立判。

::: 前提:员工类

  1. static List<Person> personList = new ArrayList<Person>();
  2. private static void initPerson() {
  3. personList.add(new Person("张三", 8, 3000));
  4. personList.add(new Person("李四", 18, 5000));
  5. personList.add(new Person("王五", 28, 7000));
  6. personList.add(new Person("孙六", 38, 9000));
  7. }

1、遍历/匹配(foreach/find/match)

Stream也是支持类似集合的遍历和匹配元素的,只是 Stream中的元素是以 Optional类型存在的。Stream的遍历、匹配非常简单。

  1. // import已省略,请自行添加,后面代码亦是
  2. public class StreamTest {
  3. public static void main(String[] args) {
  4. List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
  5. // 遍历输出符合条件的元素
  6. list.stream().filter(x -> x > 6).forEach(System.out::println);
  7. // 匹配第一个
  8. Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
  9. // 匹配任意(适用于并行流)
  10. Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
  11. // 是否包含符合特定条件的元素
  12. boolean anyMatch = list.stream().anyMatch(x -> x < 6);
  13. System.out.println("匹配第一个值:" + findFirst.get());
  14. System.out.println("匹配任意一个值:" + findAny.get());
  15. System.out.println("是否存在大于6的值:" + anyMatch);
  16. }
  17. }

2、按条件匹配filter

image.png

(1)筛选员工中已满18周岁的人,并形成新的集合

  1. /**
  2. * 筛选员工中已满18周岁的人,并形成新的集合
  3. * @思路
  4. * List<Person> list = new ArrayList<Person>();
  5. * for(Person person : personList) {
  6. * if(person.getAge() >= 18) {
  7. * list.add(person);
  8. * }
  9. * }
  10. */
  11. private static void filter01() {
  12. initPerson();
  13. List<Person> collect = personList.stream().filter(x -> x.getAge()>=18).collect(Collectors.toList());
  14. System.out.println(collect);
  15. }

image.png

(2)自定义条件匹配

image.png

3、聚合max、min、count

image.png

(1)获取String集合中最长的元素

  1. /**
  2. * 获取String集合中最长的元素
  3. * @思路
  4. * List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "sunliu");
  5. * String max = "";
  6. * int length = 0;
  7. * int tempLength = 0;
  8. * for(String str : list) {
  9. * tempLength = str.length();
  10. * if(tempLength > length) {
  11. * length = str.length();
  12. * max = str;
  13. * }
  14. * }
  15. * @return zhangsan
  16. */
  17. private static void test02() {
  18. List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "sunliu");
  19. Comparator<? super String> comparator = Comparator.comparing(String::length);
  20. Optional<String> max = list.stream().max(comparator);
  21. System.out.println(max);
  22. }

image.png

(2)获取Integer集合中的最大值

  1. //获取Integer集合中的最大值
  2. private static void test05() {
  3. List<Integer> list = Arrays.asList(1, 17, 27, 7);
  4. Optional<Integer> max = list.stream().max(Integer::compareTo);
  5. // 自定义排序
  6. Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() {
  7. @Override
  8. public int compare(Integer o1, Integer o2) {
  9. return o1.compareTo(o2);
  10. }
  11. });
  12. System.out.println(max2);
  13. }

image.png

  1. //获取员工中年龄最大的人
  2. private static void test06() {
  3. initPerson();
  4. Comparator<? super Person> comparator = Comparator.comparingInt(Person::getAge);
  5. Optional<Person> max = personList.stream().max(comparator);
  6. System.out.println(max);
  7. }

(3)获取员工中年龄最大的人

image.png

(4)计算integer集合中大于10的元素的个数

image.png

4、map与flatMap

map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
image.png

(1)字符串大写

image.png

(2)整数数组每个元素+3

  1. /**
  2. * 整数数组每个元素+3
  3. * @思路
  4. * List<Integer> list = Arrays.asList(1, 17, 27, 7);
  5. List<Integer> list2 = new ArrayList<Integer>();
  6. for(Integer num : list) {
  7. list2.add(num + 3);
  8. }
  9. @return [4, 20, 30, 10]
  10. */
  11. private static void test09() {
  12. List<Integer> list = Arrays.asList(1, 17, 27, 7);
  13. List<Integer> collect = list.stream().map(x -> x + 3).collect(Collectors.toList());
  14. System.out.println(collect);
  15. }

(3)公司效益好,每人涨2000

  1. /**
  2. * 公司效益好,每人涨2000
  3. *
  4. */
  5. private static void test10() {
  6. initPerson();
  7. List<Person> collect = personList.stream().map(x -> {
  8. x.setAge(x.getSalary()+2000);
  9. return x;
  10. }).collect(Collectors.toList());
  11. System.out.println(collect);
  12. }

(4)将两个字符数组合并成一个新的字符数组

  1. /**
  2. * 将两个字符数组合并成一个新的字符数组
  3. *
  4. */
  5. private static void test11() {
  6. String[] arr = {"z, h, a, n, g", "s, a, n"};
  7. List<String> list = Arrays.asList(arr);
  8. System.out.println(list);
  9. List<String> collect = list.stream().flatMap(x -> {
  10. String[] array = x.split(",");
  11. Stream<String> stream = Arrays.stream(array);
  12. return stream;
  13. }).collect(Collectors.toList());
  14. System.out.println(collect);
  15. }

(5)将两个字符数组合并成一个新的字符数组

  1. /**
  2. * 将两个字符数组合并成一个新的字符数组
  3. * @return [z, h, a, n, g, s, a, n]
  4. */
  5. private static void test11() {
  6. String[] arr = {"z, h, a, n, g", "s, a, n"};
  7. List<String> list = Arrays.asList(arr);
  8. List<String> collect = list.stream().flatMap(x -> {
  9. String[] array = x.split(",");
  10. Stream<String> stream = Arrays.stream(array);
  11. return stream;
  12. }).collect(Collectors.toList());
  13. System.out.println(collect);
  14. }

5、规约reduce

归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。
image.png

(1)求Integer集合的元素之和、乘积和最大值

  1. /**
  2. * 求Integer集合的元素之和、乘积和最大值
  3. *
  4. */
  5. private static void test13() {
  6. List<Integer> list = Arrays.asList(1, 2, 3, 4);
  7. //求和
  8. Optional<Integer> reduce = list.stream().reduce((x,y) -> x+ y);
  9. System.out.println("求和:"+reduce);
  10. //求积
  11. Optional<Integer> reduce2 = list.stream().reduce((x,y) -> x * y);
  12. System.out.println("求积:"+reduce2);
  13. //求最大值
  14. Optional<Integer> reduce3 = list.stream().reduce((x,y) -> x>y?x:y);
  15. System.out.println("求最大值:"+reduce3);
  16. }

(2)求所有员工的工资之和和最高工资

  1. /*
  2. * 求所有员工的工资之和和最高工资
  3. */
  4. private static void test14() {
  5. initPerson();
  6. Optional<Integer> reduce = personList.stream().map(Person :: getSalary).reduce(Integer::sum);
  7. Optional<Integer> reduce2 = personList.stream().map(Person :: getSalary).reduce(Integer::max);
  8. System.out.println("工资之和:"+reduce);
  9. System.out.println("最高工资:"+reduce2);
  10. }

6、收集(toList、toSet、toMap)

取出大于18岁的员工转为map

  1. /**
  2. * 取出大于18岁的员工转为map
  3. *
  4. */
  5. private static void test15() {
  6. initPerson();
  7. Map<String, Person> collect = personList.stream().filter(x -> x.getAge() > 18).collect(Collectors.toMap(Person::getName, y -> y));
  8. System.out.println(collect);
  9. }

7、collect

Collectors提供了一系列用于数据统计的静态方法:

计数: count

平均值: averagingInt、 averagingLong、 averagingDouble

最值: maxBy、 minBy

求和: summingInt、 summingLong、 summingDouble

统计以上所有: summarizingInt、 summarizingLong、 summarizingDouble

  1. /**
  2. * 统计员工人数、平均工资、工资总额、最高工资
  3. */
  4. private static void test01(){
  5. //统计员工人数
  6. Long count = personList.stream().collect(Collectors.counting());
  7. //求平均工资
  8. Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
  9. //求最高工资
  10. Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
  11. //求工资之和
  12. Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
  13. //一次性统计所有信息
  14. DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
  15. System.out.println("统计员工人数:"+count);
  16. System.out.println("求平均工资:"+average);
  17. System.out.println("求最高工资:"+max);
  18. System.out.println("求工资之和:"+sum);
  19. System.out.println("一次性统计所有信息:"+collect);
  20. }

8、分组(partitioningBy/groupingBy)

分区:将stream按条件分为两个 Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
image.png
将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组

  1. public class StreamTest {
  2. public static void main(String[] args) {
  3. personList.add(new Person("zhangsan",25, 3000, "male", "tieling"));
  4. personList.add(new Person("lisi",27, 5000, "male", "tieling"));
  5. personList.add(new Person("wangwu",29, 7000, "female", "tieling"));
  6. personList.add(new Person("sunliu",26, 3000, "female", "dalian"));
  7. personList.add(new Person("yinqi",27, 5000, "male", "dalian"));
  8. personList.add(new Person("guba",21, 7000, "female", "dalian"));
  9. // 将员工按薪资是否高于8000分组
  10. Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
  11. // 将员工按性别分组
  12. Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
  13. // 将员工先按性别分组,再按地区分组
  14. Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
  15. System.out.println("员工按薪资是否大于8000分组情况:" + part);
  16. System.out.println("员工按性别分组情况:" + group);
  17. System.out.println("员工按性别、地区:" + group2);
  18. }
  19. }

9、连接joining

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
image.png

10、排序sorted

将员工按工资由高到低(工资一样则按年龄由大到小)排序

  1. private static void test04(){
  2. // 按工资升序排序(自然排序)
  3. List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
  4. .collect(Collectors.toList());
  5. // 按工资倒序排序
  6. List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
  7. .map(Person::getName).collect(Collectors.toList());
  8. // 先按工资再按年龄升序排序
  9. List<String> newList3 = personList.stream()
  10. .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
  11. .collect(Collectors.toList());
  12. // 先按工资再按年龄自定义排序(降序)
  13. List<String> newList4 = personList.stream().sorted((p1, p2) -> {
  14. if (p1.getSalary() == p2.getSalary()) {
  15. return p2.getAge() - p1.getAge();
  16. } else {
  17. return p2.getSalary() - p1.getSalary();
  18. }
  19. }).map(Person::getName).collect(Collectors.toList());
  20. System.out.println("按工资升序排序:" + newList);
  21. System.out.println("按工资降序排序:" + newList2);
  22. System.out.println("先按工资再按年龄升序排序:" + newList3);
  23. System.out.println("先按工资再按年龄自定义降序排序:" + newList4);
  24. }

11、提取/组合

流也可以进行合并、去重、限制、跳过等操作。

  1. private static void test05(){
  2. String[] arr1 = { "a", "b", "c", "d" };
  3. String[] arr2 = { "d", "e", "f", "g" };
  4. Stream<String> stream1 = Stream.of(arr1);
  5. Stream<String> stream2 = Stream.of(arr2);
  6. // concat:合并两个流 distinct:去重
  7. List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
  8. // limit:限制从流中获得前n个数据
  9. List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
  10. // skip:跳过前n个数据
  11. List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());
  12. System.out.println("流合并:" + newList);
  13. System.out.println("limit:" + collect);
  14. System.out.println("skip:" + collect2);
  15. }

12、读取文件的流操作

image.png

13、计算两个list中的差集

  1. //计算两个list中的差集
  2. List<String> reduce1 = allList.stream().filter(item -> !wList.contains(item)).collect(Collectors.toList());