Search code examples
javastringbooleanbooleanquery

Simplify several boolean conditions java


how would you simplify all these conditions?

String s = "The wold is big"

if(s.contains("is") || s.contains("are") || s.contains("was") || s.contains("were")) 
{ 
    return s;
}

Since I have to check several cases like those, is there a way to simplify all those conditions?


Solution

  • I would write a utility method for that:

    public static boolean containsAny(String s, String... words) {
        for (String word : words) {
            if (s.contains(word))
                return true;
        }
        return false;
    }
    

    And now:

    if (containsAny(s, "is", "are", "was", "were")) {...}
    

    Java 8 alternative:

    if (Arrays.asList("is", "are", "was", "were").stream().anyMatch(s::contains)) {...}