10

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?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

10

Use Stream.anyMatch:

public static boolean listContainsTestWord(List<String> list, String search) {
    if (list != null && search != null) {
        return list.stream().anyMatch(search::equalsIgnoreCase);
    }
    return false;
}
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
8

You have an error because findFirst() returns an Optional<String> since your Stream pipeline is composed of String elements. As such, you can't invoke orElse with a boolean argument (only a String argument would be valid).

A direct solution to your problem would be to use

findFirst().isPresent();

This way, if findFirst() returns an empty optional, isPresent() will return false and if it does not, it will return true.

But it would be better to go with @Tagir Valeev's answer and use anyMatch.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
8

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))
Bohemian
  • 412,405
  • 93
  • 575
  • 722