我是Java 8的新手,我正在尝试以下方案。
class Numbers{
private Long userId;
private Long number1;
private Long number2;
}
List<Numbers> list = new ArrayList();
Input == {
"userId":1,
"number1":10,
"number2":20
}
{
"userId":1,
"number1":20,
"number2":40
}
输出::地图
{
"userId":1,
"sum":90 // addition of all numbers associated with userId
}
我想使用Java 8流api。
我正在尝试这样,但这给了我错误,
Map<Long, Long> hashMap =results.stream().collect(Collectors.toMap(Numbers::userId,Collectors.summingLong(?));
所以我的问题是
我可以从Collectors.toMap()
Long addNumbers(Long number1,Long number2){
return number1+number2;
}
答案 0 :(得分:10)
使用Collectors::groupingBy
和下游收集器是一种更简单的方法:
results.stream().collect(
Collectors.groupingBy(
Numbers::getUserId, Collectors.summingLong(x -> x.getNumber1() + x.getNumber2())
)
);
您仍然可以使用Collectors.toMap
来做到这一点:
results.stream().collect(
Collectors.toMap(
Numbers::getUserId,
x -> x.getNumber1() + x.getNumber2(),
Long::sum
)
);
或者没有流:
Map<Long, Long> all = new HashMap<>();
numbers.forEach(x -> all.merge(
x.getUserId(),
x.getNumber1() + x.getNumber2(),
Long::sum);