欢迎来到我的博客!

Stream API

一、什么是Stream API

1.1 简介

  • Stream API(java.util.stream)把真正的函数式编程风格引入到java中。

  • 这是对目前为止对Java类库的最好的补充。

  • 个人感觉类似SQL语句

1.2 Stream本质

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

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

1.3 注意点

  • Stream 自己不会存储元素。

  • Stream 不会改变数据源对象。相反,他们会返回一个持有结果的新Stream。

  • Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

二、Stream 的操作三个步骤

2.1、创建Stream

  • 一个数据源(如:集合、数组),获取一个流

  • 2.1.1、通过集合创建

    public void test1(){
        
            List<String> list = Arrays.asList("中国","韩国","日本","美国","俄罗斯");
    
            //返回一个顺序流
        
            Stream<String> stream = list.stream();
        
            //返回一个并行流
        
            Stream<String> parallelStream= list.parallelStream();
        
        }
    
  • 2.1.2、通过数组创建

      public void test2(){
          
            int []arr = new int[]{1,2,3,4,5,6};
          
            IntStream stream = Arrays.stream(arr);
          
        }
    
  • 2.1.3、通过Stream.of()创建

     public void test3(){
         
            Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
         
        }
    
  • 2.1.4、通过无限流创建(用的少,了解)

      public void test4(){
          
            //迭代方法
          
            //遍历前十个偶数
          
            Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);//第二个参数是Function 参数列表是T 返回也是T
          
            //生成方法
          
            Stream.generate(Math::random).limit(10).forEach(System.out::println);
          
        }
    

2.2、中间操作

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

  • 2.2.1、筛选与切片

    public void test1(){
        
            List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
        
            //filter(Predicate p) 接受lambda,从流中排除某些元素
        
            Stream<Integer> stream = list.stream();
        
            //过滤大于5的数
        
            stream.filter(e -> e > 5).forEach(System.out::println); //要加上终止操作 stream才会执行
        
            System.out.println();
        
            //limit(n) 截断流,使其元素不超过给定数量
        
            list.stream().limit(3).forEach(System.out::println);
        
            System.out.println();
        
            //skip(n) 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回空流
        
            list.stream().skip(3).forEach(System.out::println);
        
            System.out.println();
        
            //distinct() 筛选,通过流所生成的元素的 hashCode() 和 equals()来取出重复元素
        
        }
    
  • 2.2.2、映射

    public void test2(){
        
            //map(Function f)接受一个函数作为参数,将元素转化成其他形式或提取信息,该函数会被应用到每个元素
        
            List<String> list = Arrays.asList("aa","bb","cc","dd");
        
            list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
        
            //flatMap()接受一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流拼起来
        
            //map 和 flatMap 类似于list.add 和 list.addall()的区别
        
        }
    
  • 2.2.3、排序

    public void test3(){
        
            //sorter 自然排序
        
            List<Integer> list = Arrays.asList(1, 3, 2, 5, 6, 0);
        
            list.stream().sorted().forEach(System.out::println);
        
            //sorted(Comparator com) 定制排序
        
            System.out.println();
        
            list.stream().sorted((o1,o2) -> Integer.compare(o2,o1)).forEach(System.out::println);
        
        }
    

2.3、终止操作(终端操作)

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

  • 2.3.1 查找与匹配

    • allMatch(Predicate p) - 检查是否匹配所有元素。

      //练习:是否所有的员工的年龄都大于18
      
      public void test1(){ 
          
             List<Employee> employees = EmployeeDate.getEmployees();
          
             boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
          
             System.out.println(allMatch);
          
          }
      
    • anyMatch(Predicate p) -检查是否至少匹配一个元素

      //练习:是否至少有一个员工的工资大于5000	
      
      public void test2(){
              
              List<Employee> employees = EmployeeDate.getEmployees();
          
              boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 5000);
          
              System.out.println(anyMatch);
          
          }
      
    • noneMatch(Predicate p)-检查是否没有匹配的元素。

      //练习:是否存在员工姓雷
      
      public void test3(){ 
             
             List<Employee> employees = EmployeeDate.getEmployees();
          
             boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
          
             System.out.println(noneMatch);
          
          }
      
    • count-返回流中元素的总个数

      //练习:求工资大于5000的员工数
      
      public void test4(){ 
          
             List<Employee> employees = EmployeeDate.getEmployees();
          
             long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
          
             System.out.println(count);
          
          }
      
    • max(Comparator c)-返回流中的最大值

      //练习:返回最高的工资
      
      public void test4(){ 
             
             List<Employee> employees = EmployeeDate.getEmployees();
          
             Optional<Double> max = employees.stream().map(e -> e.getSalary()).max(Double::compare);
          
             System.out.println(max);
          
          }
      
    • min(Comparator c)-返回流中的最小值

      //练习:返回工资最低的员工
      
      public void test5(){ 
          
             Optional<Employee> min = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
          
             System.out.println(min);
          
          }
      
    • forEach(Consumer c)-内部迭代

      public void test6(){ 
          
             List<Employee> employees = EmployeeDate.getEmployees();
          
             employees.stream().forEach(System.out::println);
          
          }
      
  • 2.3.2 归约

    • reduce(T identity, BinaryOperator)-可以将流中元素反复结合进去,得到一个值。返回这个值

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

      public void test2(){
          
               //练习2:计算公司所有员工工资的和
          
              List<Employee> employees = EmployeeDate.getEmployees();
          
              Stream<Double> doubleStream = employees.stream().map(Employee::getSalary);
          
              Optional<Double> reduce1 = doubleStream.reduce(Double::sum);
          
              System.out.println(reduce1);
       
          }  
             
      
  • 2.3.3收集

    • collect(Collector c)-将流转换为其他形式。接收一个Collector接口的实现,返回这个对应的类型

      public void test1(){
              //练习1:查找大于6000的员工,结果返回一个List
          
              List<Employee> employees = EmployeeDate.getEmployees();
          
              List<Employee> collect = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
          
              collect.forEach(System.out::println);
          
              //练习2:查找大于6000的员工,结果返回一个Set
          
              Set<Employee> collect1 = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
          
              collect1.forEach(System.out::println);
          }
      
posted @   Espoirr  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
--> //烟花
点击右上角即可分享
微信分享提示