saurabh agarwal
saurabh agarwal

Reputation: 2174

Sum of list of object fields using stream

I have a object

Class DummyObject() {
    double first;
    double second;
    double third;
    double fourth;
}

Class SomeObject() {
    List<DummyObject> objectList;
}

Class HighestObject() {
    List<SomeObject> objectList;
}

A variable of type SomeObject is given. I have to find out if sum of four field in DummyObject is not getting equal to amount X.

using for loop, It can easily be written like:

for(SomeObject someObject : hightestObject.getObjectList()) {
    for(DummyObject dummyObject : someObject.getObjectList()){
        if((dummyObject.first + dummyObject.second + dummyObject.third + dummyObject.fourth) != X) {
             return false;
        }
    }
}

How can we do it using java stream ?

Upvotes: 2

Views: 375

Answers (2)

user4910279
user4910279

Reputation:

Try this.

return hightestObject.getObjectList().stream()
    .flatMap(someObject -> someObject.getObjectList().stream())
    .allMatch(dummyObject ->
        dummyObject.first + dummyObject.second + dummyObject.third + dummyObject.fourth == X);

Upvotes: 2

assylias
assylias

Reputation: 328598

You could combine flatMap and anyMatch:

HighestObject h = ...;

boolean foundNotX = h.getObjectList().stream() //Stream<SomeObject>
                  .flatMap(so -> so.getObjectList().stream()) //Stream<DummyObject>
                  .mapToDouble(o -> o.first + o.second + o.third + o.fourth) //DoubleStream
                  .anyMatch(sum -> sum != X);
if (foundNotX) return false;

Depending on what you are after, using .allMatch(sum -> sum == X) might be more appropriate.

Upvotes: 2

Related Questions