如何使用Java 8 Streams和Lambdas迭代嵌套for循环引用父元素?

RIT*_*AVI 5 lambda java-8 java-stream

我有下面的代码.

public static ModuleKey getDeployableModuleFromModulesList(List<Module> modules) {
        ModuleKey deployableModuleKey = null;
        for(Module module : modules) {
            List<Artifact> artifacts = module.getArtifacts();
            for(Artifact artifact : artifacts) {
                if(artifact.getType().equals("ear")) {
                    return module.getKey();
                } else if(!artifact.getType().equals("ear")) {
                    if(artifact.getType().equals("war")) {
                        deployableModuleKey = module.getKey();
                    } 
                }
            }
        }
        return deployableModuleKey;
    }
Run Code Online (Sandbox Code Playgroud)

此代码使用key ='war'找到第一个'deployableModuleKey',或者使用key ='war'找到最后一个'deployableModuleKey'.我想使用Java 8 Streams和Lambdas实现与上面相同的功能.

到目前为止,我所尝试的是:

modules.stream().flatMap(e -> e.getArtifacts().stream())
  .filter(e -> e.getType().equals("ear")).findFirst()
  .orElseGet(() -> modules.stream().flatMap(e -> e.getArtifacts().stream())
  .filter(e -> e.getType().equals("war")).reduce((a, b) -> b).orElse(null));
Run Code Online (Sandbox Code Playgroud)

上面的代码片段将返回一个类型的对象Artifact而不是Module.我想获得工件与条件匹配的模块.一旦找到模块,我就可以通过这样做来返回密钥module.getKey().要做到这一点,我想知道我们如何引用父for循环的元素.

我不确定我的Java 8代码是否完全正确.
在这方面有人可以帮助我吗?

RIT*_*AVI 0

我已经找到了解决我的问题的方法。

public static ModuleKey getDeployableModuleFromModulesList(List<Module> modules) {
    Optional<ModuleKey> op = modules.stream().filter(module -> module.getArtifacts().stream().anyMatch(artifact -> artifact.getType().equals("ear"))).map(module -> module.getKey()).findFirst();
    if (!op.isPresent()) {
        op = modules.stream().filter(module -> module.getArtifacts().stream().anyMatch(artifact -> artifact.getType().equals("war"))).map(module -> module.getKey()).reduce((a, b) -> b);
    }
    return op.orElse(null);
}
Run Code Online (Sandbox Code Playgroud)

无论如何,也欢迎其他解决方案。如果有人添加另一个解决方案,我会尝试所有这些。