.._.stream().map">
当前位置:   article > 正文

Java8 Stream 总结_.stream().map

.stream().map

Java8 Stream 思维导图

目录

1、Stream 创建

 2、Stream 使用

2.1遍历/匹配(foreach/find/match)

 2.2筛选(filter)

2.3聚合(max/min/count)

2.4 映射(map/flatMap)

2.5归约(reduce)

2.6收集(collect)

2.6.1归集(toList/toSet/toMap)

2.6.2统计(count/averaging)

2.6.3分组(partitioningBy/groupingBy)

2.6.4接合(joining)

2.6.5归约(reducing)

2.7排序(sorted)

2.8提取/组合


1、Stream 创建

方式一:通过 java.util.Collection.stream() 方法用集合创建流

  1. /**
  2. * 创建方式一:通过 java.util.Collection.stream() 方法用集合创建流
  3. */
  4. List<String> list = Arrays.asList("a", "b", "c", "d");
  5. // 创建一个顺序流
  6. Stream<String> stream = list.stream();
  7. stream.forEach(System.out::println);
  8. // 创建一个并行流
  9. Stream<String> parallelStream = list.parallelStream();
  10. parallelStream.forEach(System.out::println);

方式二:通过java.util.Arrays.stream(T[] array)方法用数组创建流

  1. int[] array = {1,2,3,4,5,6};
  2. IntStream intStream = Arrays.stream(array);
  3. intStream.forEach(System.out::println);

方式三:通过Stream的静态方法:of()、iterate()、generate()

  1. Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
  2. integerStream.forEach(System.out::println);
  3. Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(4);
  4. stream2.forEach(System.out::println);
  5. Stream<Double> stream3 = Stream.generate(Math::random).limit(3);
  6. stream3.forEach(System.out::println);

stream和parallelStream区分:

1、stream是顺序流,由主线程按顺序对流执行操作。
2、parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,前提是流中的数据处理没有顺序要求。

 运行流程图说明:

知识点拓展:

通过parallel()把顺序流转换成并行流。

 2、Stream 使用

员工类实体定义

  1. package com.zzg.entity;
  2. import java.io.Serializable;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Builder;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. @Data
  8. @AllArgsConstructor
  9. @NoArgsConstructor
  10. @Builder
  11. @SuppressWarnings("serial")
  12. public class Person implements Serializable {
  13. private String name; // 姓名
  14. private int salary; // 薪资
  15. private int age; // 年龄
  16. private String sex; //性别
  17. private String area; // 地区
  18. }

2.1遍历/匹配(foreach/find/match)

Stream支持类似集合的遍历和匹配元素。

  1. /**
  2. * 温馨提示:Stream中的元素是以Optional类型存在
  3. */
  4. // List<Integer> list = Arrays.asList(1,2,3,4,5);
  5. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
  6. /**
  7. * 遍历输出符合条件的元素
  8. */
  9. list.stream().filter(x -> x > 6).forEach(System.out::println);
  10. /**
  11. * 输出符合条件的第一个元素
  12. */
  13. Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
  14. /**
  15. * 输出符合条件的任意元素(适用于并行流)
  16. */
  17. Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
  18. /**
  19. * 判断是否包含符合特定条件的元素
  20. */
  21. boolean anyMatch = list.stream().anyMatch(x -> x > 6);
  22. System.out.println("匹配第一个值:" + findFirst.orElse(0));
  23. System.out.println("匹配任意一个值:" + findAny.orElse(0));
  24. System.out.println("是否存在大于6的值:" + anyMatch);

 2.2筛选(filter)

筛选,按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作。

  1. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
  2. /**
  3. * 案例一:筛选出Integer集合中 大于8的元素,并打印出来
  4. */
  5. list.stream().filter(x -> x > 8).forEach(System.out::println);
  6. /**
  7. * 案例二:筛选薪资大于8000的员工名称,构建新的集合 温馨提示:map 用于获取指定对象的属性值 collect 用于构建新的集合
  8. */
  9. List<Person> dataList = init();
  10. List<String> names = dataList.stream().filter(item -> item.getSalary() > 8000).map(item -> item.getName())
  11. .collect(Collectors.toList());
  12. names.stream().forEach(System.out::println);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.3聚合(max/min/count)

对集合、数组的数据进行统计操作。

  1. /**
  2. * 案例三:获取员工集合中姓名字符串最长。
  3. */
  4. String name = dataList.stream().map(item -> item.getName()).collect(Collectors.toList()).stream()
  5. .max(Comparator.comparing(String::length)).orElse("");
  6. System.out.println("用户名称:" + name);
  7. /**
  8. * 案例四: 获取Integer 最大值
  9. */
  10. List<Integer> sortList = Arrays.asList(7, 6, 9, 4, 11, 6);
  11. // 自然排序
  12. Optional<Integer> max = sortList.stream().max(Integer::compareTo);
  13. // 自定义排序
  14. Optional<Integer> max2 = sortList.stream().max(new Comparator<Integer>() {
  15. @Override
  16. public int compare(Integer o1, Integer o2) {
  17. return o1.compareTo(o2);
  18. }
  19. });
  20. System.out.println("自然排序的最大值:" + max.orElse(0));
  21. System.out.println("自定义排序的最大值:" + max2.orElse(0));
  22. /**
  23. * 案例五: 获取员工集合中工资最高
  24. */
  25. Optional<Person> salary = dataList.stream().max(Comparator.comparingInt(Person::getSalary));
  26. /**
  27. * 基于lombok 创建模式构建Person 对象并赋值Salary 初始值
  28. */
  29. System.out.println("员工工资最大值:" + salary.orElse(Person.builder().salary(0).build()).getSalary());
  30. /**
  31. * 案例六:统计Integer集合中大于6的元素的个数
  32. */
  33. List<Integer> integerList = Arrays.asList(7, 6, 4, 8, 2, 11, 9);
  34. long integerCount = integerList.stream().filter(item -> item >= 6).count();
  35. System.out.println("integer 集合大于6个数:" + integerCount);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.4 映射(map/flatMap)

映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为mapflatMap

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

  1. /**
  2. * 案例七:遍历字符串列表,通过','逗号分隔符构建新列表
  3. */
  4. List<String> strList = Arrays.asList("A,B,C", "D,E,F");
  5. List<String> newStrList = strList.stream().flatMap(item -> {
  6. return Arrays.stream(item.split(","));
  7. }).collect(Collectors.toList());
  8. newStrList.stream().forEach(System.out::println);

2.5归约(reduce)

实现对集合求和、求乘积和求最值操作

  1. /**
  2. * 案例八: 统计员工集合工资总数 温馨提示: 通过reduce 实现数值归纳总结,实现对集合求和、求乘积和求最值操作
  3. */
  4. Integer totalSalary = dataList.stream().map(Person::getSalary).collect(Collectors.toList()).stream()
  5. .reduce(Integer::sum).orElse(0);
  6. System.out.println("员工集合工资总数:" + totalSalary);
  7. /**
  8. * reduce 归纳统计使用匿名函数
  9. */
  10. Integer totalSalaryTwo = dataList.stream().map(Person::getSalary).collect(Collectors.toList()).stream()
  11. .reduce((x, y) -> x + y).orElse(0);
  12. System.out.println("员工集合工资总数:" + totalSalaryTwo);
  13. /**
  14. * reduce 归纳统计求最大值
  15. */
  16. Integer totalSalaryThree = dataList.stream().map(Person::getSalary).collect(Collectors.toList()).stream()
  17. .reduce(Integer::max).orElse(0);
  18. System.out.println("员工工资最高:" + totalSalaryThree);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.6收集(collect)

collect就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。

collect主要依赖java.util.stream.Collectors类内置的静态方法。

2.6.1归集(toList/toSet/toMap)

  1. List<String> nameList = dataList.stream().map(Person::getName).collect(Collectors.toList());
  2. nameList.stream().forEach(System.out::println);
  3. Map<String, Person> mapNameObject = dataList.stream().collect(Collectors.toMap(Person::getName, item -> item));
  4. /**
  5. * java8 遍历map
  6. */
  7. mapNameObject.forEach((k, v) -> {
  8. System.out.println("员工姓名:" + k);
  9. System.out.println("toString():" + v.toString());
  10. });
  11. Set<Person> setObject = dataList.stream().collect(Collectors.toSet());
  12. /**
  13. * java8 遍历set
  14. */
  15. setObject.forEach(item -> {
  16. System.out.println("toString():" + item.toString());
  17. });
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.6.2统计(count/averaging)

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

  • 计数:count
  • 平均值:averagingInt、averagingLong、averagingDouble
  • 最值:maxBy、minBy
  • 求和:summingInt、summingLong、summingDouble
  • 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
  1. // 求总数
  2. Long count = dataList.stream().collect(Collectors.counting());
  3. // 求平均工资
  4. Double average = dataList.stream().collect(Collectors.averagingDouble(Person::getSalary));
  5. // 求最高工资
  6. Optional<Integer> max3 = dataList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
  7. // 求工资之和
  8. Integer sum = dataList.stream().collect(Collectors.summingInt(Person::getSalary));
  9. // 一次性统计所有信息
  10. DoubleSummaryStatistics collect = dataList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
  11. System.out.println("员工总数:" + count);
  12. System.out.println("员工工资最高:" + max3);
  13. System.out.println("员工平均工资:" + average);
  14. System.out.println("员工工资总和:" + sum);
  15. System.out.println("员工工资所有统计:" + collect);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.6.3分组(partitioningBy/groupingBy)

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

  1. // 将员工按薪资是否高于8000分组
  2. Map<Boolean, List<Person>> part = dataList.stream()
  3. .collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
  4. // 将员工按性别分组
  5. Map<String, List<Person>> group = dataList.stream().collect(Collectors.groupingBy(Person::getSex));
  6. // 将员工先按性别分组,再按地区分组
  7. Map<String, Map<String, List<Person>>> group2 = dataList.stream()
  8. .collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
  9. System.out.println("员工按薪资是否大于8000分组情况:" + part);
  10. System.out.println("员工按性别分组情况:" + group);
  11. System.out.println("员工按性别、地区:" + group2);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.6.4接合(joining)

joining将stream中的元素用特定的连接符连接成一个字符串。

  1. String nameJoin = dataList.stream().map(Person::getName).collect(Collectors.joining(","));
  2. System.out.println("拼接员工姓名:" + nameJoin);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.6.5归约(reducing)

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

  1. Integer sum1 = dataList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));
  2. System.out.println("员工扣税薪资总和:" + sum1);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));
  9. return personList;
  10. }

2.7排序(sorted)

sorted,排序操作。支持两种排序:

  • sorted():自然排序,流中元素需实现 Comparable 接口

  • sorted(Comparator com):Comparator 排序器自定义排序

  1. // 按工资升序排序(自然排序)
  2. List<String> newList = dataList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
  3. .collect(Collectors.toList());
  4. // 按工资倒序排序
  5. List<String> newList2 = dataList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
  6. .map(Person::getName).collect(Collectors.toList());
  7. // 先按工资再按年龄升序排序
  8. List<String> newList3 = dataList.stream()
  9. .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
  10. .collect(Collectors.toList());
  11. // 先按工资再按年龄自定义排序(降序)
  12. List<String> newList4 = dataList.stream().sorted((p1, p2) -> {
  13. if (p1.getSalary() == p2.getSalary()) {
  14. return p2.getAge() - p1.getAge();
  15. } else {
  16. return p2.getSalary() - p1.getSalary();
  17. }
  18. }).map(Person::getName).collect(Collectors.toList());
  19. System.out.println("按工资升序排序:" + newList);
  20. System.out.println("按工资降序排序:" + newList2);
  21. System.out.println("先按工资再按年龄升序排序:" + newList3);
  22. System.out.println("先按工资再按年龄自定义降序排序:" + newList4);
  1. public static List<Person> init() {
  2. List<Person> personList = new ArrayList<Person>();
  3. personList.add(new Person("Tom", 8900, 25, "male", "New York"));
  4. personList.add(new Person("Jack", 7000, 21, "male", "Washington"));
  5. personList.add(new Person("Lily", 7800, 29, "female", "Washington"));
  6. personList.add(new Person("Anni", 8200, 31, "female", "New York"));
  7. personList.add(new Person("Owen", 9500, 35, "male", "New York"));
  8. personList.add(new Person("Alisa", 7900, 51, "female", "New York"));

2.8提取/组合

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/352296
推荐阅读
相关标签
  

闽ICP备14008679号