Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

Calculate the sum of a field contained in a collection that is contained in an other collection using Java Stream

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...