I have three class ie Engine , Wheel and AutoMobile . The contents of these classes are as follows:-
class Engine {
String modelId;
}
class Wheel {
int numSpokes;
}
class AutoMobile {
String make;
String id;
}
I have a List<Engine>
, a List<Wheel>
and a List<Automobile>
which I have to iterate through and check for a particular condition. If there is one entity that satisfies this condition, I have to return true; otherwise the function returns false.
The function is as follows:
Boolean validateInstance(List<Engine> engines, List<Wheel> wheels , List<AutoMobile> autoMobiles) {
for(Engine engine: engines) {
for(Wheel wheel : wheels) {
for(AutoMobile autoMobile : autoMobiles) {
if(autoMobile.getMake().equals(engine.getMakeId()) && autoMobile.getMaxSpokes() == wheel.getNumSpokes() && .... ) {
return true;
}
}
}
}
return false;
}
I have till now tried out this
return engines.stream()
.map(engine -> wheels.stream()
.map(wheel -> autoMobiles.stream()
.anyMatch( autoMobile -> {---The condition---})));
I know map() is not the proper function to be used . I am at a loss as to how to solve this scenario. I have gone through the api documentation and have tried forEach() with no result. I have gone through the reduce() api , but I am not sure how to use it
I know the map converts one stream to another stream , which should not be done . Can anyone suggest how to solve this scenario.
You should nest Stream::anyMatch
:
return engines.stream()
.anyMatch(engine -> wheels.stream()
.anyMatch(wheel -> autoMobiles.stream()
.anyMatch(autoMobile -> /* ---The condition--- */)));
你应该使用flatMap,而不是Map。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.