简体   繁体   English

将嵌套循环转换为Java 8流

[英]Converting nested loops to Java 8 streams

I have following nested for loops which I need to convert to declarative code. 我有以下嵌套for循环,我需要转换为声明代码。

for (String variable : variables ){
      boolean validAttribute = false;
      if(variable.equals(SOME_CONSTANT)){
          validAttribute = true;
      }
      else {
         for(String attrName: attrNames){
            if(variableName.equals(attrName)){
                validAttribute = true;
                break;
            }
         }
      }
      if(!validAttribute){
          return false;
      }
 }

I am able to achieve it some how using the flatMap . 我能够实现一些如何使用flatMap But doesn't seem efficient as the earlier for loop use to break at the first non-matching entry. 但是,在第一个不匹配的条目中,循环使用的早期似乎并不高效。 Is there any other simpler way? 还有其他更简单的方法吗?

(Also the code below seems difficult to understand) (以下代码似乎很难理解)

List<String> inValidVariables = attrNames.stream().flatMap(attrName -> variableNames.stream()
                            .filter(variableName -> !variableName.equals(attrName) && !variableName.equals(SOME_CONSTANT)))
                            .collect(Collectors.toList());
 return inValidVariables.size() ==0;

Personally i would solve this like that 就个人而言,我会这样解决这个问题

    variables.stream().allMatch((item) -> item.equals(SOME_CONSTANT) 
                                || attrNames.contains(item));

I think streams should make your task easier not more complicated, that is reason why i didn't use it for inner loop as you can refactor this. 我认为流应该让你的任务变得更容易而不是更复杂,这就是为什么我没有将它用于内循环,因为你可以重构它。

here is link to ideone where you can run both methods 这里是ideone的链接 ,您可以在其中运行这两种方法

I think this should match your requirement: 我认为这应符合您的要求:

variables.stream().noneMatch(variable-> !variable.equals(CONSTANT)&&attrNames.stream().noneMatch(attrName -> variable.equals(attrName)));

returns true if the each variable is equals the CONSTANT or one of the attrNames. 如果每个变量等于CONSTANT或其中一个attrNames,则返回true

else it returns false (if ther is any variable which doesnt match the CONSTANT or any attrName) 否则它返回false (如果是任何与CONSTANT或任何attrName不匹配的变量)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM