我有三个类别,即 Engine 、 Wheel 和 AutoMobile 。这些类的内容如下:-
class Engine {
String modelId;
}
class Wheel {
int numSpokes;
}
class AutoMobile {
String make;
String id;
}
我有一个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;
}
到目前为止我已经尝试过这个
return engines.stream()
.map(engine -> wheels.stream()
.map(wheel -> autoMobiles.stream()
.anyMatch( autoMobile -> {---The condition---})));
我知道map()不是正确使用的函数。我不知道如何解决这种情况。我已经浏览了 api 文档并尝试了 forEach() 但没有结果。我已经了解了reduce() api,但我不知道如何使用它
我知道映射将一个流转换为另一个流,这是不应该做的。任何人都可以建议如何解决这种情况。
最佳答案
您应该嵌套Stream::anyMatch
:
return engines.stream()
.anyMatch(engine -> wheels.stream()
.anyMatch(wheel -> autoMobiles.stream()
.anyMatch(autoMobile -> /* ---The condition--- */)));
关于java - 将返回 boolean 值的嵌套 for 循环转换为 java 8 流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43736684/