Java 8遍历列表,根据字段进行过滤并求和

问题描述 投票:-1回答:1

我想遍历列表,根据特定字段进行过滤并求和

class Transaction {

       private String heading;
       private LocalDate date;
       private BigDecimal amount;

       }

我有这样的交易清单:

COLLECTIONS, 14-05-2020, 250
COLLECTIONS, 14-05-2020, 150
TAXES, 14-05-2020, 200,
COLLECTIONS, 15-05-2020, 300

预期结果

COLLECTIONS, 14-05-2020, 400
TAXES, 14-05-2020, 200
COLLECTIONS, 15-05-2020, 300

这是我到目前为止所做的,我创建了一个基于字段过滤的新列表

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;
}

这是我的过滤列表

transactions.stream().filter(distinctByKey(pr -> Arrays.asList(pr.getHeading(), pr.getDate())))
  .collect(Collectors.toList())
java arraylist java-8 stream
1个回答
0
投票

您可以使用三个参数执行toMap收集器。确实,您应该首先按heading属性分组,并为地图中的重复键求和amount属性。最后获得地图值。

Collection<Transaction> result = list.stream()
             .collect(Collectors.toMap(
                       Transaction::getHeading,
                       Function.identity(),
                       (t1,t2)->{t1.setAmount(t1.getAmount()+t2.getAmount());retuen t1;})
                     ).values();
© www.soinside.com 2019 - 2024. All rights reserved.