• JDK8新特性之Stream流


    目录

    集合处理数据的弊端

    Stream流的获取方式

    对于Collection的实现类

    对于Map

    对于数组

    Stream常用方法介绍

    count

    forEach

    filter

    limit

    skip

    map

    sorted

    distinct

    match

    find

    max和min

    reduce

    mapToInt

    concat

    Stream结果收集

    结果收集到集合中

    结果收集到数组中

    对流中的数据做聚合计算

    对流中数据做分组操作

    对流中的数据做分区操作

    对流中的数据做拼接

    并行的Stream流

    串行的Stream流

    并行流

    线程安全问题


    集合处理数据的弊端

    当我们在需要对集合中的元素进行操作的时候,除了必需的添加,删除,获取外,最典型的操作就是 集合遍历

    看这个例子:

    1. public class StreamTest1 {
    2. @Test
    3. public void test() {
    4. // 定义一个List集合
    5. List list = Arrays.asList("张三", "张三丰", "成龙", "周星驰");
    6. // 1.获取所有 姓张的信息
    7. List list1 = new ArrayList<>();
    8. for (String s : list) {
    9. if (s.startsWith("张")) {
    10. list1.add(s);
    11. }
    12. }
    13. // 2.获取名称长度为3的用户
    14. List list2 = new ArrayList<>();
    15. for (String s : list1) {
    16. if (s.length() == 3) {
    17. list2.add(s);
    18. }
    19. }
    20. // 3. 输出满足条件的所有用户的信息
    21. for (String s : list2) {
    22. System.out.println(s);
    23. }
    24. }
    25. }

    上面的代码针对与我们不同的需求总是一次次的循环循环循环.这时我们希望有更加高效的处理方式,这 时我们就可以通过JDK8中提供的Stream API来解决这个问题了。

    Stream更加优雅的解决方案:

    1. @Test
    2. public void test2(){
    3. List list = Arrays.asList("张三", "张三丰", "成龙", "周星驰");
    4. list.stream()
    5. .filter(s->s.startsWith("张"))
    6. .filter(s->s.length()==3)
    7. .forEach(System.out::println);
    8. }

    看上面的代码够简短吧。获取流,过滤张,过滤长度,逐一打印。代码相比于上面的案例更加的简 洁直观,接下来我们就来学习学习stream流

    Stream流的获取方式

    对于Collection的实现类

    首先,java.util.Collection 接口中加入了default方法 stream,也就是说Collection接口下的所有的实 现都可以通过steam方法来获取Stream流。

    1. public class getStreamTest {
    2. @Test
    3. public void test1(){
    4. ArrayList objects = new ArrayList<>();
    5. objects.stream();
    6. HashSet objects1 = new HashSet<>();
    7. objects1.stream();
    8. Vector objects2 = new Vector<>();
    9. objects2.stream();
    10. }
    11. }
    12. 对于Map

      Map接口别没有实现Collection接口,那这时怎么办呢?这时我们可以根据Map的 entrySet() 方法获取对应的key value的集合。

      1. @Test
      2. public void test2(){
      3. HashMap map = new HashMap<>();
      4. map.entrySet().stream();
      5. }

      初学者可能不太好理解这个entrySet方法。这样想,map本来是存放一组组键值对的一个容器嘛,那我们要对容器里面的键值对进行遍历,但是遍历不了哇,要么就只能遍历键,要么就只能遍历值,无法完成我们的需求,所以有了entrySet方法,用来将map容器里面的这些键值对一组组的分好,这么一看,是不是这个容器就类似Collection了,这样我们每次遍历的时候每一项都是一个键值对映射项。看下面这个例子:

      对于数组

      在实际开发中我们不可避免的还是会操作到数组中的数据,由于数组对象不可能添加默认方法,所 有Stream接口中提供了静态方法of。

      1. @Test
      2. public void test3(){
      3. String[] a={"aa","bb","cc"};
      4. Stream a1 = Stream.of(a);
      5. a1.forEach(System.out::println);
      6. Integer[] b={1,23,8,5};
      7. Stream b1 = Stream.of(b);
      8. b1.forEach(System.out::println);
      9. //基本数据类型不行
      10. int[] c={1,5,3,6};
      11. Stream<int[]> c1 = Stream.of(c);
      12. c1.forEach(System.out::println);
      13. }

      但是注意:基本数据类型的数组不行,必须要是包装数据类型数组。

      Stream常用方法介绍

      Stream流的操作很丰富,这里只介绍一些常用的API。这些方法可以被分成两种:

      终结方法:返回值类型不再是 Stream 类型的方法,不再支持链式调用,常用的有count方法和forEach方法。

      非终结方法:返回值类型仍然是 Stream 类型的方法,支持链式调用。除了终结方法以外的都是非终结方法。

      Stream注意事项(重要):

      • Stream只能操作一次
      • Stream方法返回的是新的流
      • Stream不调用终结方法,中间的操作不会执行

      count

      该方法返回一个long值,表示元素的个数

      1. public static void main(String[] args) {
      2. long count = Stream.of("a1", "a2", "a3").count();
      3. System.out.println(count);
      4. }

      forEach

      该方法接收一个Consumer函数式接口,会将元素遍历交给函数处理

      1. public static void main(String[] args) {
      2. Stream.of("a1", "a2", "a3").forEach(System.out::println);;
      3. }

      filter

      filter方法的作用是用来过滤数据的。返回符合条件的数据。该接口接收一个Predicate函数式接口参数作为筛选条件

      1. public static void main(String[] args) {
      2. Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
      3. .filter((s)->s.contains("a"))
      4. .forEach(System.out::println);
      5. }

      limit

      参数是一个long类型的数值,对该集合的前n个元素进行截取

      1. public static void main(String[] args) {
      2. Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
      3. .limit(3)
      4. .forEach(System.out::println);
      5. }

      skip

      参数是一个long类型的数值,对该集合的前n个元素进行跳过,和limit恰好相反

      1. public static void main(String[] args) {
      2. Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
      3. .skip(3)
      4. .forEach(System.out::println);
      5. }

      map

      该接口需要一个Function函数式接口参数,然后对元素进行遍历操作

      1. @Test
      2. public void test4(){
      3. String[] str= {"cc2","2cl2","3vv"};
      4. List collect = Stream.of(str).map(String::length).collect(Collectors.toList());
      5. System.out.println(collect);
      6. }

      sorted

      对数据进行排序,默认是可以自然排序,也可以自己实现排序规则

      1. @Test
      2. public void test5(){
      3. Integer[] a={1,8,2,6,58,6};
      4. Stream.of(a)
      5. //.sorted() //默认为自然排序
      6. .sorted((i,j)->j-i)//自定义规则,这里我们是逆序
      7. .forEach(System.out::println);
      8. }

      distinct

      对数据进行去重操作。

      Stream流中的distinct方法对于基本数据类型是可以直接出重的,但是对于自定义类型,我们是需要重写hashCode和equals方法来定义规则。

      1. @Test
      2. public void test6(){
      3. Integer[] a={1,8,2,6,58,6};
      4. Stream.of(a)
      5. //.sorted() //默认为自然排序
      6. .sorted((i,j)->j-i)//自定义规则,这里我们是逆序
      7. .distinct()
      8. .forEach(System.out::println);
      9. }

      match

      如果需要判断数据是否匹配指定的条件,可以使用match相关的方法

      boolean anyMatch(Predicate predicate); // 元素是否有任意一个满足条件 boolean allMatch(Predicate predicate); // 元素是否都满足条件

      boolean noneMatch(Predicate predicate); // 元素是否都不满足条件

      1. public static void main(String[] args) {
      2. boolean b = Stream.of("1", "3", "3", "4", "5", "1", "7")
      3. .map(Integer::parseInt)
      4. //.allMatch(s -> s > 0)
      5. //.anyMatch(s -> s >4)
      6. .noneMatch(s -> s > 4);
      7. System.out.println(b);
      8. }

      注意match是一个终结方法

      find

      如果我们需要找到某些数据,可以使用find方法来实现

      Optional findFirst();

      Optional findAny();

      1. public static void main(String[] args) {
      2. Optional first = Stream.of("1", "3", "3", "4", "5", "1","7").findFirst();
      3. System.out.println(first.get());
      4. Optional any = Stream.of("1", "3", "3", "4", "5", "1","7").findAny();
      5. System.out.println(any.get());
      6. }

      max和min

      如果我们想要获取最大值和最小值,那么可以使用max和min方法

      Optional min(Comparator comparator);

      Optional max(Comparator comparator);

      1. public static void main(String[] args) {
      2. Optional max = Stream.of("1", "3", "3", "4", "5", "1", "7")
      3. .map(Integer::parseInt)
      4. .max((o1,o2)->o1-o2);
      5. System.out.println(max.get());
      6. Optional min = Stream.of("1", "3", "3", "4", "5", "1", "7")
      7. .map(Integer::parseInt)
      8. .min((o1,o2)->o1-o2);
      9. System.out.println(min.get());
      10. }

      reduce

      如果需要将所有数据归纳得到一个数据,可以使用reduce方法

      1. public static void main(String[] args) {
      2. Integer sum = Stream.of(4, 5, 3, 9)
      3. // identity默认值
      4. // 第一次的时候会将默认值赋值给x
      5. // 之后每次会将 上一次的操作结果赋值给x y就是每次从数据中获取的元素
      6. .reduce(0, (x, y) -> {
      7. System.out.println("x="+x+",y="+y);
      8. return x + y;
      9. });
      10. System.out.println(sum);
      11. // 获取 最大值
      12. Integer max = Stream.of(4, 5, 3, 9)
      13. .reduce(0, (x, y) -> {
      14. return x > y ? x : y;
      15. });
      16. System.out.println(max);
      17. }

      mapToInt

      如果需要将Stream中的Integer类型转换成int类型,可以使用mapToInt方法来实现

      1. public static void main(String[] args) {
      2. // Integer占用的内存比int多很多,在Stream流操作中会自动装修和拆箱操作
      3. Integer arr[] = {1, 2, 3, 5, 6, 8};
      4. Stream.of(arr)
      5. .filter(i -> i > 0)
      6. .forEach(System.out::println);
      7. // 为了提高程序代码的效率,我们可以先将流中Integer数据转换为int数据,然后再操作
      8. IntStream intStream = Stream.of(arr)
      9. .mapToInt(Integer::intValue);
      10. intStream.filter(i -> i > 3)
      11. .forEach(System.out::println);
      12. }

      concat

      如果有两个流,希望合并成为一个流,那么可以使用Stream接口的静态方法concat

      1. public static void main(String[] args) {
      2. Stream stream1 = Stream.of("a","b","c");
      3. Stream stream2 = Stream.of("x", "y", "z");
      4. // 通过concat方法将两个流合并为一个新的流
      5. Stream.concat(stream1,stream2).forEach(System.out::println);
      6. }

      Stream结果收集

      结果收集到集合中

      1. @Test
      2. public void test7(){
      3. List list = Stream.of("a", "b", "c")
      4. .collect(Collectors.toList());
      5. System.out.println(list);
      6. Set set = Stream.of("a", "b", "c")
      7. .collect(Collectors.toSet());
      8. System.out.println(set);
      9. ArrayList arrayList = Stream.of("a", "b", "c")
      10. .collect(Collectors.toCollection(ArrayList::new));
      11. System.out.println(arrayList);
      12. HashSet hashSet = Stream.of("a", "b", "c")
      13. .collect(Collectors.toCollection(HashSet::new));
      14. System.out.println(hashSet);
      15. }

      结果收集到数组中

      Stream中提供了toArray方法来将结果放到一个数组中,返回值类型是Object[],如果我们要指定返回的 类型,那么可以使用另一个重载的toArray(IntFunction f)方法

      1. @Test
      2. public void test8(){
      3. Object[] objects = Stream.of("a", "b", "c")
      4. .toArray();
      5. System.out.println(objects);
      6. String[] strings = Stream.of("a", "b", "c")
      7. .toArray(String[]::new);
      8. System.out.println(strings);
      9. }

      对流中的数据做聚合计算

      1. @Test
      2. public void test9() {
      3. // 获取年龄的最大值
      4. Optional maxAge = Stream.of(
      5. new Person("张三", 18)
      6. , new Person("李四", 22)
      7. , new Person("张三", 13)
      8. , new Person("王五", 15)
      9. , new Person("张三", 19)
      10. ).collect(Collectors.maxBy((p1, p2) -> p1.getAge() - p2.getAge()));
      11. System.out.println("最大年龄:" + maxAge.get());
      12. // 获取年龄的最小值
      13. Optional minAge = Stream.of(
      14. new Person("张三", 18)
      15. , new Person("李四", 22)
      16. , new Person("张三", 13)
      17. , new Person("王五", 15)
      18. , new Person("张三", 19)
      19. ).collect(Collectors.minBy((p1, p2) -> p1.getAge() - p2.getAge()));
      20. System.out.println("最新年龄:" + minAge.get());
      21. // 求所有人的年龄之和
      22. Integer sumAge = Stream.of(
      23. new Person("张三", 18)
      24. , new Person("李四", 22)
      25. , new Person("张三", 13)
      26. , new Person("王五", 15)
      27. , new Person("张三", 19)
      28. ).collect(Collectors.summingInt(Person::getAge));
      29. System.out.println("年龄总和:" + sumAge);
      30. // 年龄的平均值
      31. Double avgAge = Stream.of(
      32. new Person("张三", 18)
      33. , new Person("李四", 22)
      34. , new Person("张三", 13)
      35. , new Person("王五", 15)
      36. , new Person("张三", 19)
      37. ).collect(Collectors.averagingInt(Person::getAge));
      38. System.out.println("年龄的平均值:" + avgAge);
      39. // 统计数量
      40. Long count = Stream.of(
      41. new Person("张三", 18)
      42. , new Person("李四", 22)
      43. , new Person("张三", 13)
      44. , new Person("王五", 15)
      45. , new Person("张三", 19)
      46. ).filter(p -> p.getAge() > 18)
      47. .collect(Collectors.counting());
      48. System.out.println("满足条件的记录数:" + count);
      49. }

      对流中数据做分组操作

      当我们使用Stream流处理数据后,可以根据某个属性将数据分组

      1. @Test
      2. public void test10() {
      3. // 根据账号对数据进行分组
      4. Map> map1 = Stream.of(
      5. new Person("张三", 18, 175)
      6. , new Person("李四", 22, 177)
      7. , new Person("张三", 14, 165)
      8. , new Person("李四", 15, 166)
      9. , new Person("张三", 19, 182)
      10. ).collect(Collectors.groupingBy(Person::getName));
      11. map1.forEach((k, v) -> System.out.println("k=" + k + "\t" + "v=" + v));
      12. // 根据年龄分组 如果大于等于18 成年否则未成年
      13. Map> map2 = Stream.of(
      14. new Person("张三", 18, 175)
      15. , new Person("李四", 22, 177)
      16. , new Person("张三", 14, 165)
      17. , new Person("李四", 15, 166)
      18. , new Person("张三", 19, 182)
      19. ).collect(Collectors.groupingBy(p -> p.getAge() >= 18 ? "成年" : "未成年"));
      20. map2.forEach((k, v) -> System.out.println("k=" + k + "\t" + "v=" + v));
      21. }

      对流中的数据做分区操作

      Collectors.partitioningBy会根据值是否为true,把集合中的数据分割为两个列表,一个true列表,一个 false列表

      1. @Test
      2. public void test11() {
      3. Map> map = Stream.of(
      4. new Person("张三", 18, 175)
      5. , new Person("李四", 22, 177)
      6. , new Person("张三", 14, 165)
      7. , new Person("李四", 15, 166)
      8. , new Person("张三", 19, 182)
      9. ).collect(Collectors.partitioningBy(p -> p.getAge() > 18));
      10. map.forEach((k, v) -> System.out.println(k + "\t" + v));
      11. }

      对流中的数据做拼接

      Collectors.joining会根据指定的连接符,将所有的元素连接成一个字符串

      1. @Test
      2. public void test12() {
      3. String s1 = Stream.of(
      4. new Person("张三", 18, 175)
      5. , new Person("李四", 22, 177)
      6. , new Person("张三", 14, 165)
      7. , new Person("李四", 15, 166)
      8. , new Person("张三", 19, 182)
      9. ).map(Person::getName)
      10. .collect(Collectors.joining());
      11. // 张三李四张三李四张三
      12. System.out.println(s1);
      13. String s2 = Stream.of(
      14. new Person("张三", 18, 175)
      15. , new Person("李四", 22, 177)
      16. , new Person("张三", 14, 165)
      17. , new Person("李四", 15, 166)
      18. , new Person("张三", 19, 182)
      19. ).map(Person::getName)
      20. .collect(Collectors.joining("_"));
      21. // 张三_李四_张三_李四_张三
      22. System.out.println(s2);
      23. String s3 = Stream.of(
      24. new Person("张三", 18, 175)
      25. , new Person("李四", 22, 177)
      26. , new Person("张三", 14, 165)
      27. , new Person("李四", 15, 166)
      28. , new Person("张三", 19, 182)
      29. ).map(Person::getName)
      30. .collect(Collectors.joining("_", "###", "$$$"));
      31. // ###张三_李四_张三_李四_张三$$$
      32. System.out.println(s3);
      33. }

      并行的Stream流

      串行的Stream流

      我们前面使用的Stream流都是串行,也就是在一个线程上面执行。

      1. @Test
      2. public void test01(){
      3. Stream.of(5,6,8,3,1,6)
      4. .filter(s->{
      5. System.out.println(Thread.currentThread() + "" + s);
      6. return s > 3;
      7. }).count();
      8. }

      Thread[main,5,main]5

      Thread[main,5,main]6

      Thread[main,5,main]8

      Thread[main,5,main]3

      Thread[main,5,main]1

      Thread[main,5,main]6

      并行流

      parallelStream其实就是一个并行执行的流,它通过默认的ForkJoinPool,可以提高多线程任务的速度。

      我们可以通过两种方式来获取并行流:

      • 通过List接口中的parallelStream方法来获取
      • 通过已有的串行流转换为并行流(parallel)

      1. @Test
      2. public void test02(){
      3. List list = new ArrayList<>();
      4. // 通过List 接口 直接获取并行流
      5. Stream integerStream = list.parallelStream();
      6. // 将已有的串行流转换为并行流
      7. Stream parallel = Stream.of(1, 2, 3).parallel();
      8. }

      测试:

      1. @Test
      2. public void test03(){
      3. Stream.of(1,4,2,6,1,5,9)
      4. .parallel() // 将流转换为并发流,Stream处理的时候就会通过多线程处理
      5. .filter(s->{
      6. System.out.println(Thread.currentThread() + " s=" +s);
      7. return s > 2;
      8. }).count();
      9. }

      Thread[main,5,main] s=1

      Thread[ForkJoinPool.commonPool-worker-2,5,main] s=9 Thread[ForkJoinPool.commonPool-worker-6,5,main] s=6 Thread[ForkJoinPool.commonPool-worker-13,5,main] s=2 Thread[ForkJoinPool.commonPool-worker-9,5,main] s=4 Thread[ForkJoinPool.commonPool-worker-4,5,main] s=5 Thread[ForkJoinPool.commonPool-worker-11,5,main] s=1

      线程安全问题

      在多线程的处理下,肯定会出现数据安全问题。如下:

      1. @Test
      2. public void test9(){
      3. ArrayList arrayList1 = new ArrayList<>();
      4. for (int i=0;i<1000;i++){
      5. arrayList1.add(i);
      6. }
      7. ArrayList arrayList2 = new ArrayList<>();
      8. arrayList1.parallelStream()
      9. .forEach(arrayList2::add);
      10. System.out.println(arrayList2.size());
      11. }

      运行以后结果并不是1000

      针对这个问题,我们的解决方案有哪些呢?

      • 加同步锁
      • 使用线程安全的容器
      • 通过Stream中的toArray/collect操作

      1. //加同步锁
      2. @Test
      3. public void test9() {
      4. Object o = new Object();
      5. ArrayList arrayList1 = new ArrayList<>();
      6. for (int i = 0; i < 1000; i++) {
      7. arrayList1.add(i);
      8. }
      9. ArrayList arrayList2 = new ArrayList<>();
      10. arrayList1.parallelStream()
      11. .forEach((a) -> {
      12. synchronized (o) {
      13. arrayList2.add(a);
      14. }
      15. });
      16. System.out.println(arrayList2.size());
      17. }

      1. //使用线程安全的容器
      2. @Test
      3. public void test10() {
      4. Vector objects = new Vector<>();
      5. for (int i = 0; i < 1000; i++) {
      6. objects.add(i);
      7. }
      8. Vector vector = new Vector<>();
      9. objects.parallelStream()
      10. .forEach((a) -> {
      11. vector.add(a);
      12. });
      13. System.out.println(vector.size());
      14. }

      1. //将线程不安全的容器包装为线程安全的容器
      2. @Test
      3. public void test11() {
      4. List listNew = new ArrayList<>();
      5. List synchronizedList = Collections.synchronizedList(listNew);
      6. IntStream.rangeClosed(1, 1000)
      7. .parallel()
      8. .forEach(i -> {
      9. synchronizedList.add(i);
      10. });
      11. System.out.println(synchronizedList.size());
      12. }

      1. //通过Stream中的 toArray方法或者 collect方法来操作
      2. @Test
      3. public void test12() {
      4. List list = IntStream.rangeClosed(1, 1000)
      5. .parallel()
      6. .boxed()
      7. .collect(Collectors.toList());
      8. System.out.println(list.size());
      9. }

    13. 相关阅读:
      解决方案:AI赋能工业生产3.0,从工业“制造”到“智造”
      Java安全—CommonsCollections1
      LeetCode - 二维数组及滚动数组
      C++笔记之文档术语——将可调用对象作为函数参数
      基于三维GIS开发的水电工程建设方案
      获取所有非manager的员工emp_no
      Linux系统下centos中在线添加硬盘后不重启在线扩容linux系统目录不重启系统
      IDEA04:动态加载配置文件
      安装jdk、tomcat、mysql
      从心灰意冷到自学Java3个月顺利拿到offer,多亏这份文档
    14. 原文地址:https://blog.csdn.net/weixin_56644618/article/details/127984094