I am novice to java 8.I am trying below scenario.
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
}
output:: Map
{
"userId":1,
"sum":90 // addition of all numbers associated with userId
}
I want to use java 8 stream api.
I am trying like this but it gives me error,
Map<Long, Long> hashMap =results.stream().collect(Collectors.toMap(Numbers::userId,Collectors.summingLong(?));
So my question,
Can i invoke below method from Collectors.toMap()
Long addNumbers(Long number1,Long number2){
return number1+number2;
}
There is an easier way with Collectors::groupingBy
with a downstream collector:
results.stream().collect(
Collectors.groupingBy(
Numbers::getUserId, Collectors.summingLong(x -> x.getNumber1() + x.getNumber2())
)
);
You can still do it with Collectors.toMap
:
results.stream().collect(
Collectors.toMap(
Numbers::getUserId,
x -> x.getNumber1() + x.getNumber2(),
Long::sum
)
);
Or without streams :
Map<Long, Long> all = new HashMap<>();
numbers.forEach(x -> all.merge(
x.getUserId(),
x.getNumber1() + x.getNumber2(),
Long::sum);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With