Search code examples
javastringjava-streamoption-typeignore-case

How to return a default boolean value in java streams if element not found?


I want to determine if a given string matches - ignoring case - one of the elements in a List<String>.

I'm trying to achieve this with Java 8 streams. Here's my attempt using .orElse(false):

public static boolean listContainsTestWord(List<String> list, String search) {
    if (list != null && search != null) {
        return list.stream().filter(value -> value.equalsIgnoreCase(search))
          .findFirst().orElse(false);
    }
    return false;
}

but that doesn't compile.

How should I code it to return whether a match is found or not?


Solution

  • It's a one-liner:

    public static boolean listContainsTestWord(List<String> list, String search) {
        return list != null && search != null && list.stream().anyMatch(search::equalsIgnoreCase);
    }
    

    Don't even bother with a method:

    if (list != null && search != null && list.stream().anyMatch("someString"::equalsIgnoreCase))