转换将布尔返回到Java 8流的嵌套的for循环? [英] Convert a nested for loop that returns boolean to java 8 stream?

查看:77
本文介绍了转换将布尔返回到Java 8流的嵌套的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3类,即Engine,Wheel和AutoMobile.这些类的内容如下:-

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;
}

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

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.

功能如下:

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---})));

我知道map()不是要使用的正确函数.我不知道如何解决这种情况.我已经阅读了api文档,并尝试了forEach()没有任何结果.我已经查看了reduce()API,但不确定如何使用它

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.

推荐答案

您应嵌套Stream::anyMatch:

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

这篇关于转换将布尔返回到Java 8流的嵌套的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆