Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting nested loops to Java 8 streams

I have following nested for loops which I need to convert to declarative code.

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. 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;
like image 680
sidgate Avatar asked Jul 16 '15 13:07

sidgate


2 Answers

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

like image 190
user902383 Avatar answered Oct 28 '22 20:10

user902383


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.

else it returns false (if ther is any variable which doesnt match the CONSTANT or any attrName)

like image 43
griFlo Avatar answered Oct 28 '22 21:10

griFlo