public static void main(String[] args) {
//java stream 实现list分组求和后并取最大值
List<HitRuleConfig> list = new ArrayList<>();
list.add(new HitRuleConfig("1", "1", new BigDecimal(1), 1));
list.add(new HitRuleConfig("1", "1", new BigDecimal(1), 2));
list.add(new HitRuleConfig("2", "2", new BigDecimal(1), 3));
list.add(new HitRuleConfig("2", "2", new BigDecimal(1), 4));
list.add(new HitRuleConfig("1", "1", new BigDecimal(1), 5));
list.add(new HitRuleConfig("3", "3", new BigDecimal(1), 6));
list.add(new HitRuleConfig("3", "3", new BigDecimal(1), 7));
//分组求最大
Map<String, HitRuleConfig> configMap = list.parallelStream().filter(Objects::nonNull).
collect(Collectors.groupingBy(a -> a.getAppId() + a.getTest(),
Collectors.collectingAndThen(Collectors.reducing((c1, c2) -> (c1.getVersionSort() > c2.getVersionSort()) ? c1 : c2), Optional::get)));
//将map转换为list
List<HitRuleConfig> list2 = new ArrayList<>();
configMap.forEach((k, v) -> {
list2.add(v);
});
//全量过滤最先的数据list 然后在求和
List<HitRuleConfig> list3 = new ArrayList<>();
for (HitRuleConfig f : list2) {
List<HitRuleConfig> collect = list.stream().filter(a -> a.getAppId().equals(f.getAppId()) && a.getTest().equals(f.getTest())).collect(Collectors.toList());
BigDecimal reduce = collect.stream().map(HitRuleConfig::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
f.setAmount(reduce);
list3.add(f);
}
System.out.println(list3);
}
java stream 实现list分组求和后并取最大值
最新推荐文章于 2024-08-29 17:22:24 发布