I want to calculate the sum of a field contained in a collection that is contained in another collection using java stream().
i only know how to do it if the calculated field is directly in the first collection, like this :
return collectionOfObjectA.stream()
.mapToDouble(c1 -> c1.getSalary()).sum();
but now the "collectionOfObjectA" contain another "collectionOfObjectB", and this last one is the one containing "salary" field.
ObjectA:
{
id:1,
Collection<ObjectB>
}
and ObjectB:
{
id:1,
salary: 4000
}
the way i'm calculating it now is like follow:
Double result=0.0;
for (ObjectA obj: collectionOfObjectA())
{
for(ObjectB objB : objA.getcollectionOfObjectB()){
result+= objB.getSalary();
}
}
return result;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…