Reputation: 2174
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
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
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