Steam流的基本用法 - yiyanglij/yiyanglij.github.io GitHub Wiki

Stream.map()

将得到的所有ID收集起来,成一个新的List集合保存到另一个stream流保存起来

    List<Long> labelIdList=couponLabelList.stream().map(CouponLabel::getLabelId).distinct().collect(Collectors.toList());

Stream.filter()

将满足条件的保存到一个新的stream流中保存起来

    goodsDtVo.getGoodsUnitVoList().stream()
            .filter(goodsUnitVo -> goodsUnitVo.getGoodsUnit().equals(goodsDtVo.getGoodsUnit()))
            .collect(Collectors.toList()).stream().findFirst()
            .ifPresent(val->goodsDtVo.setPrice(val.getPrice()));
    IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
            .filter(n -> n % 2 != 0)
            .forEach(System.out::println);

Stream.reduce()

不同于其他的是:他是一个聚合函数,一般将得到的结果再进行计算,得到一个新的stream流保存起来

   List<Integer> integers=Arrays.asList(1,2,3,4,5,6,7,8,9,10);
   Integer reduce = integers.stream().reduce(0,(integer1,integer2) ->integer1+integer2);
   System.out.println(reduce);

计算对象中属性的价格

reduct(初始值,数据类型::对应的操作)

   BigDecimal sum=id1.stream().map(x ->x.getGoodsOrigtinalPrice()).reduce(BigDecimal.ZERO,BigDecimal::add);

获取最大值/获取最小值

方法一

   Optional<Integer> max1=integers.stream().reduce(Integer::max);
   if(max1.isPresent){
        System.out.println(max1);
   }

方法二

   Optional<Integer> max2=integers.stream().max(Integer::compareTo);
   if(max1.isPresent){
        System.out.println(max2);
   }

List转Map

   	Map<String, User> userMap= userList.stream().collect(Collectors.toMap(User::getName, Function.identity(),(key1, key2)->key2));

Map转List

    List<User> userList = userMap.entrySet().stream().map(e ->e.getValue()).collect(Collectors.toList());

做判断的几种方法

有一个满足条件返回true

    userList.stream().anyMatch(user -> user.getHeight() > 175);

全部满足返回true

    userList.stream().allMatch(user -> user.getHeight() > 175);

都不满足返回true

    userList.stream().noneMatch(user -> user.getHeight() > 175);
⚠️ **GitHub.com Fallback** ⚠️