lambda常用的流操作

  • 1.collect 根据stream里面的值生成一个列表

    collect方法通常结合Collector结合一起使用,是一个通用的强大结构,可以满足数据转换、数据分组、字符串处理等操作

    生成集合:

    List<String,Object> list=Stream.of("a","b","c").collect(Collectors.toList())
    

    集合转换:

    TreeSet<String> treeSet=list.stream().collect(Collectors.toCollection(TreeSet::new));
    

    转换成值:

    List<Integer> list=stream.of("a","b","c").collect(Collectors.toList());
    String maxChar=list.stream().collect(Collectors.maxBy(String::compare));
    

    数据分块

    List<Integer> collected=Stream.of(1,2,3,4,5,6,7).collect(Collectors.toList())
    Map<Boolean,List<Integer>> divided=collected.stream().collect(Collectors.partitionBy(e -> e>5));
    

    字符串处理

    List<String> list=Stream.of("a","b","c").collect(Collectors.toList())
    String format=list.stream().collect(Collectors.joining(",","[","]"))    
    
  • 2.map 将数据流中的对象转化为一个新的流对象

    List<String> collected=Stream.of("a","b","c").collect(Collectors.toList());
    List<String> upperList = collected.stream().map(e-> e.toUpperCase()).collect(Collectors.toList());
    
  • 3.flatmap 与map功能类似,只不过map对应的是一个流,而flatmap可以对应多个流

    List<String> collected=Stream.of("a","b","c").collect(Collectors.toList());
    List<String> collected2=Stream.of("c","d","e").collect(Collectors.toList());
    List<List<String>> strSet=Arrays.asList(collected,collected2);
    List<String> flatMap=strSet.stream().flatMap(plist -> plist.stream().collect(Collectors.toList());
    
  • 4.filter 通过过滤条件筛选流中的对象

    List<Integer> collected=Stream.of(1,2,3,4,5,6,7).collect(Collectors.toList())
    List<Integer> nums=collected.stream().filter(e ->e>5).collect(Collectors.toList));    
    
  • 5.max/min 求最大值和最小值

    List<Integer> collected=Stream.of(1,2,3,4,5,6,7).collect(Collectors.toList())
    Integer max=number.stream().max(Comparator.comparing(k ->k)).get();
    Integer min=number.stream().min(Comparator.comparing(k ->k)).get();
    
  • 6.reduce 从流中生成一个值

    int sum =Stream.of(1,2,3,4,5,6,7).reduce(0,(acc,e) -> acc+ e)
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值