将一个返回布尔值的嵌套for循环转换为java 8流?

Ech*_*cho 3 java java-8 java-stream

我有三个类,即Engine,Wheel和AutoMobile.这些课程的内容如下: -

class Engine {
     String modelId;
 }

class Wheel {
     int numSpokes;
 }

class AutoMobile {
      String make;
      String id;
}
Run Code Online (Sandbox Code Playgroud)

我有一个List<Engine>,一个List<Wheel>和一个List<Automobile>我必须迭代并检查特定条件.如果有一个实体满足这个条件,我必须返回true; 否则该函数返回false.

功能如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

我到现在为止都试过这个

 return engines.stream()
        .map(engine -> wheels.stream()
          .map(wheel -> autoMobiles.stream()
              .anyMatch( autoMobile -> {---The condition---})));
Run Code Online (Sandbox Code Playgroud)

我知道map()不是正确使用的函数.我不知道如何解决这个问题.我已经浏览了api文档并尝试了forEach()而没有结果.我已经完成了reduce()api,但我不知道如何使用它

我知道地图将一个流转换为另一个流,这不应该完成.任何人都可以建议如何解决这个问题.

Flo*_*own 5

你应该嵌套Stream::anyMatch:

return engines.stream()
    .anyMatch(engine -> wheels.stream()
      .anyMatch(wheel -> autoMobiles.stream()
          .anyMatch(autoMobile -> /* ---The condition--- */)));
Run Code Online (Sandbox Code Playgroud)

  • @Echo`Stream :: anyMatch`是一种短路终端操作.如果最里面的`anyMatch`匹配,它会传播到最外层,就像嵌套for循环中的return语句一样. (2认同)