给定一个类项目,如下:
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分组,但我不确定现在如何按日期过滤,所以如果有任何帮助,我将不胜感激。
否则,我可以使用基本的循环来完成,但我希望找到一种更好的方法,如果可能的话,使用Java8。
发布于 2018-08-10 13:14:55
你可以这样做,
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值?你将如何处理这种冲突?
https://stackoverflow.com/questions/51779108
复制相似问题