Converts a nested loop that returns a boolean to java 8 stream?

I have three classes ie Engine, Wheel and AutoMobile. The content of these classes is as follows: -

class Engine {
     String modelId;
 }

class Wheel {
     int numSpokes;
 }

class AutoMobile {
      String make;
      String id;
}

      

I have List<Engine>

, a List<Wheel>

and a List<Automobile>

, which I have to iterate over and check for a specific condition. If there is one entity that satisfies this condition, I must 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 tried this so far

 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 don't understand how to solve this scenario. I went through the api documentation and tried forEach () with no result. I went through the reduce () api but I'm not sure how to use it.

I know the map will convert one stream to another stream, which shouldn't be done. Can anyone suggest how to solve this scenario.

+3


source to share


2 answers


You need to attach Stream::anyMatch

:



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

      

+5


source


You should be using flatMap, not a map.



-1


source







All Articles