Before mapToDouble
you have to use flatMap
like this:
return collection1.stream()
.flatMap(cA -> cA.getCollectionB().stream())
.mapToDouble(ObjectB::getSalary)
.sum();
Or you can use map
before the flatMap
:
return collection1.stream()
.map(ObjectA::getCollectionB)
.flatMap(List::stream)
.mapToDouble(ObjectB::getSalary)
.sum();
Of you can use flatMapToDouble
directly as @Naman mentioned:
return collection1.stream()
.flatMapToDouble(
cA -> cA.getCollectionB().stream().mapToDouble(ObjectB::getSalary)
).sum();
5
solved Calculate the sum of a field contained in a collection that is contained in an other collection using Java Stream