Java根据属性对项目列表进行汇总

时间:2018-08-10 04:44:54

标签: collections java-8 java-stream

给出一个类别项,如下所示:

Class item {
 private Date date;
 private String id;
 private Double value;

 // getter and setter...
}

我想创建一个函数,该函数遍历项目列表,并对具有相同日期和ID的项目的值求和,然后返回ID列表和值的总和。

public Map<String, Double> process(List<Item> listItems, Date today) {
 // return list with ID and sum of the value for all the items group by ID and where the date equals the date in parameter.
}

到目前为止,我已经研究了Java 8函数Stream和Collect并能够做到这一点:

Map<String, Double> map = listTransactions.stream()
                .collect(Collectors.groupingBy(Item::getId, Collectors.summingDouble(Item::getValue)));

按ID分组可以很好地工作,但是现在我不确定如何按日期进行过滤,因此不胜感激。

否则,我可以使用基本循环来完成此操作,但我想找到一种更好的方法,如果可能的话,使用Java 8。

1 个答案:

答案 0 :(得分:1)

您可以这样做

Map<String, Map<LocalDateTime, Double>> result = items.stream()
        .collect(Collectors.groupingBy(Item::getId,
                Collectors.groupingBy(Item::getDate, Collectors.summingDouble(Item::getValue))));

但是结果类型与您所需的不完全相同。在这种情况下,它是Map<String, Map<LocalDateTime, Double>>

无论如何,这是我的问题,在这种情况下,您将如何处理具有不同日期值的相同ID值?您将如何处理该冲突?

相关问题