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;
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With