关于list.Stream的用法(去重,相加,分组)

1.通过list中的某个字段来对list分组,然后得到多组数据
Map<String, List<WmsStockRefundItem>> refundMap = itemList.stream().collect(Collectors.groupingBy(WmsStockRefundItem::getSupplyNumber));
Map > refundMap = itemList.stream().collect(Collectors.groupingBy(WmsStockRefundItem::getSupplyNumber));

2.通过list中的某个属性过滤去重,只留下不同的集合

List<WmsStockRefundItem> fiterList =list.stream().filter(distinctByKey(b -> b.getProdNumber())).collect(Collectors.toList());
//通过属性去重 private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
          
       Map<Object,Boolean> seen = new ConcurrentHashMap<>();     return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }
List fiterList =list.stream().filter(distinctByKey(b -> b.getProdNumber())).collect(Collectors.toList()); //通过属性去重 private static Predicate distinctByKey(Function keyExtractor) { Map seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }

3.相加list中的某个值 bigdecimal

BigDecimal totalquantity = list.stream().map(WmsStockRefundItem::getReqQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalquantity = list.stream().map(WmsStockRefundItem::getReqQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);

4.相加list中的某个值 Integer

Integer num=list.stream().collect(Collectors.summingInt(WmsStockRefundItem::getReqQuantity))
Integer num=list.stream().collect(Collectors.summingInt(WmsStockRefundItem::getReqQuantity))
1.通过list中的某个字段来对list分组,然后得到多组数据 Map > refundMap = itemList.stream().collect(Collectors.groupingBy(WmsStockRefundItem::getSupplyNumber)); 2.通过list中的某个属性过滤去重,只留下不同的集合 List fiterList =list.stream().filter(distinctByKey(b -> b.getProdNumber())).collect(Collectors.toList()); //通过属性去重 private static Predicate distinctByKey(Function keyExtractor) { Map seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } 3.相加list中的某个值 bigdecimal BigDecimal totalquantity = list.stream().map(WmsStockRefundItem::getReqQuantity).reduce(BigDecimal.ZERO, BigDecimal::add); 4.相加list中的某个值 Integer Integer num=list.stream().collect(Collectors.summingInt(WmsStockRefundItem::getReqQuantity))
经验分享 程序员 微信小程序 职场和发展