java 怎么通过stream流对数组进行各种操作汇总

  • Post author:
  • Post category:java


根据数组中字段进行分组,然后对另一个字段进行求和(BigDecimal)

List<CategoryDangerVo> categoryCityDangerVos = new ArrayList<>();

Map<String, CategoryDangerVo> dangerVoMap = categoryCityDangerVos.stream().
                collect(Collectors.groupingBy(CategoryDangerVo::getBciCategory, Collectors.collectingAndThen(Collectors.toList(), m -> {

                    CategoryDangerVo categoryDangerVo = new CategoryDangerVo();
                    categoryDangerVo.setBciCategory(m.get(0).getBciCategory());            
                    categoryDangerVo.setNum(m.stream().map(CategoryDangerVo::getNum).
                    reduce(BigDecimal.ZERO, BigDecimal::add));
                    return categoryDangerVo;
                })));

根据数组中字段进行分组,然后对另一个字段进行求和(普通数值类型,用上面那种方式也可以实现)

Map<String, Long> statisticsAreaMap = 
totalNum.stream().collect( Collectors.groupingBy(
CategoryDangerVo::getArea, 
Collectors.summingLong(CategoryDangerVo::getCount)
));

使用filter去重

    /**
     * 去重
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    private static <T> Predicate<T> distinctByVariable(Function<? super T, ?> keyExtractor) {
        HashMap<Object, Boolean> map = new HashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }


list.stream().filter(distinctByVariable(Mod::getName));



版权声明:本文为l784283324原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。