Convert a nested for loop that returns boolean to java 8 stream?

孤者浪人 提交于 2020-06-25 05:46:06

问题


I have three class i.e. 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.


回答1:


You should nest Stream::anyMatch:

return engines.stream()
    .anyMatch(engine -> wheels.stream()
      .anyMatch(wheel -> autoMobiles.stream()
          .anyMatch(autoMobile -> /* ---The condition--- */)));



回答2:


You should be using flatMap, not Map.



来源:https://stackoverflow.com/questions/43736684/convert-a-nested-for-loop-that-returns-boolean-to-java-8-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!