JAVA -- lambda和Stream Api的简单使用

自java 8 开始支持lambda语法并提供了函数式接口和Stream Api。
lambda使得我们的开发过程更加迅速、代码更简洁、而且在某些功能的实现上极大的缩短了我们的工作量。
但是其缺点也是显而易见的,不好的编码习惯会使得代码的可读性变差、不便于调试等。

Lambda语法

(int x,int y)->{
    
    
	x = x+1;
	y = y+1;
	return x/y;
}
当返回信息只有一行代码时,可以省略return和大括号
1. 不需要参数,返回值为 10
() -> 10 
2. 接收一个参数,括号可以省略
x -> 4 * x  
3. 接收2int型整数求和
(int x, int y) -> x + y   
4. 执行一个操作,不返回值
(String s) -> System.out.print(s)

Stream Api 常用操作

stream api的引入极大的方便了我们对集合的操作,支持并行parallel(),使用时要注意线程安全问题,他所提供的接口能满足我们的大部分需求。

  • 创建一个流 包含但不限于以下方法
    //IntStream、LongStream等内置类创建一个流
    IntStream.rangeClosed(1,10).boxed();
    //通过已经存在的List创建
    list.stream();
    //通过数组创建 如果数组是基本类型的要加boxed装箱
    Arrays.stream(arr).boxed();
    Stream.of(arr);
    
  • filter 过滤
    //过滤信息 返回成功的数据才能被收集
    List<Integer> result=IntStream.rangeClosed(1,10).boxed()
    									.filter(e->e>5)//获取流中大于五的数
    									.collect(Collectors.toList());
    
  • map/flapMap 映射/平铺
    //使用map将数字转化为其他类型或格式 将一个元素转化为另一个元素
    List<String> result=IntStream.rangeClosed(1,10).boxed()
    									.map(e-> "数字"+ e++ +"加1之后是"+String.valueOf(e))
    									.collect(Collectors.toList());
    //flatMap则是将元素内容铺平,有些情况下,我们流中的元素还是一个集合或者数组,当对这个元素操作时,我们可能还需要再进行一次循环,flatmap就是将二位转为一维去处理。
    int[] ss = new int[5];
    ss[0] =1;
    ss[1] =2;
    int[] ss2 = new int[5];
    ss2[0] =11;
    ss2[1] =21;
    List<int[]> list= new ArrayList<>();
    list.add(ss);
    list.add(ss2);
    //打印list中的数组内容
    list.stream().flatMap(in-> Arrays.stream(in.clone()).boxed())
    .forEach(System.out::println);
    
  • forEach 循环
    //Stream的每一个元素都执行该表达式 
    List<Integer> result=IntStream.rangeClosed(1,10).boxed()
    									.forEach(e->System.out.println(e));
    
  • reduce 整合
    //求和操作
    IntStream.rangeClosed(1,10).boxed().reduce((x,y)->x+y);
    
  • limit/skip 限制/跳过
    //Stream的每一个元素都执行该表达式 
    List<Integer> result=IntStream.rangeClosed(1,10).boxed()
    									.skip(2)//跳过两个元素
    									.limit(3)//限制三个元素通过
    									.forEach(e->System.out.println(e));
    
  • sorted 排序
    	//正序
      IntStream.rangeClosed(1,10).boxed()
              .sorted().forEach(e-> System.out.println("e = " + e));
      //倒序
      IntStream.rangeClosed(1,10).boxed()
              .sorted(Comparator.reverseOrder()).forEach(e-> System.out.println("e = " + e));
    	```
    
  • distinct 去重
    	//去重 peek对元素之行操作但不影响元素
    	//打印结果是 先执行peek在执行foreach 一个一个元素交叉进行
    	Random random = new Random();
      IntStream.rangeClosed(1,10).boxed().map(e->random.nextInt(5))
                    .peek(i->System.out.println("随机数是: "+i)).distinct()
                    .forEach(e->System.out.println("去重结果为: "+ e));
    	```
    
  • max/min 最大值/最小值
    //随机1-10整数的最大值
    System.out.println("random = " + IntStream.rangeClosed(1,10).max());
    //随机1-10整数的最小值
    System.out.println("random = " + IntStream.rangeClosed(1,10).min());
    
  • findFirst 查找符合条件的第一个,返回Optional
    //用Optional接收 可以接收null
    Optional<Integer> result=IntStream.rangeClosed(1,10).boxed()
    									.filter(e->e>5)//获取流中大于五的数
    									.findFirst();
    //判断结果是否是null
    if(result.isPresent()){
          
          
      //获取结果内容
        System.out.println("result ="+result.get());
    }
    

收集器 Collect

  • Collectors.toCollection()

    //整理为集合
      Stream.of(1,2,3,4,5,6,8,9,0).collect(Collectors.toCollection(ArrayList::new));
       Stream.of(1,2,3,4,5,6,8,9,0).collect(Collectors.toCollection(HashSet::new));
       //可以简化为
       Stream.of(1,2,3,4,5,6,8,9,0).collect(Collectors.toList());
       Stream.of(1,2,3,4,5,6,8,9,0).collect(Collectors.toSet());
       //toMap类似
    
  • Collectors.joining() 聚合

     //价格字符串拼接 用,隔开
     Stream.of(1,2,3).collect(Collectors.joining(","));//1,2,3
     //增加前缀后缀
     Stream.of(1,2,3).collect(Collectors.joining(",","[","]"));//[1,2,3]
    
  • Collectors.counting() 统计

      //价格字符串拼接 用,隔开
         Stream.of(1,2,3).collect(Collectors.counting());//3
    
  • Collectors.minBy()/maxBy() 最大最小值

         //价格字符串拼接 用,隔开
         IntStream.rangeClosed(1,10).boxed()
         .collect(Collectors
         .minBy(new Comparator<Integer>() {
          
          
    			@Override
    			public int compare(Integer o1, Integer o2) {
          
          
    			        //比较操作
    			        return o1-o2;
    			        }
    			        }));
    
  • Collectors.summingInt()/summarizingLong()/summarizingDouble() 求和

    //求和
    Stream.of(1,2,3).collect(Collectors.summingInt(Integer::valueOf));//6
    
  • Collectors.averagingInt()/averagingDouble()/averagingLong() 求平均值

    //求平均值
    Stream.of(1,2,3).collect(Collectors.averagingInt(Integer::valueOf));//2.0
    
  • Collectors.groupingBy() 分组

    //按照某个指标分组
    //Student
    list.stream().collect(Collectors.groupingBy(Student::getScore));//根据成绩分组学生
    list.stream().collect(Collectors.groupingBy(e->{
          
          e.getBj()+e.getScore()}));//根据班级和成绩分组
    
  • Collectors.partitioningBy() 分区

    //根据条件是否成立分为 true和false
    //返回Map<Boolean,List<Integer>>
    Stream.of(1,2,3).collect(Collectors.partitioningBy(e->e>2));
    

猜你喜欢

转载自blog.csdn.net/qq_40096897/article/details/121316648