ezhil
ezhil

Reputation: 1083

Set value based on all conditions inside FOR loop

I need to set boolean value only when all the conditions are set. I am struggling to set the boolean value inside the for loop. As per my code the value is set TRUE/FALSE based on last item in the list. But the value should set only when all conditions are set. Could someone help me on this?

boolean validateName(List<String> NameList, Name name) {
        boolean value = false;
        for (String name : NameList) {
            name.hasName(name);
            value = true;
        }
        return value;
}

Upvotes: 0

Views: 409

Answers (3)

Arnaud
Arnaud

Reputation: 17534

Return false as soon as one condition is not met.

boolean validateName(List<String> NameList, Name aName) {
        boolean value = false;
        for (String name : NameList) {
            if(!aName.hasName(name))
              return false;

        }
        return true;
}

Upvotes: 2

Matt
Matt

Reputation: 1308

Try this:

boolean validateName(List<String> nameList, Name name) {
   for (String nameTmp : nameList) {
      if(!nameTmp.equals(name))
         return false;
   }
   return true;
}

Upvotes: 2

Prashant
Prashant

Reputation: 5383

Try this if you are using Java 8:

return NameList.stream().allMatch(element -> element.equals(name))

Upvotes: 0

Related Questions