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

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

I am trying to achieve this using Java 8 threads. Here is 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 it does not compile.

How can I encode it to return if a match is found?

+4
source share
3 answers

This is single line:

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

Do not interfere with the method:

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

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;
}
+6
source

, findFirst() Optional<String>, Stream String. , orElse boolean ( String).

A direct solution to your problem would be to use

findFirst().isPresent();

Thus, if it findFirst()returns an empty optional parameter, it 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.

+2
source

Source: https://habr.com/ru/post/1619162/


All Articles