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

10,907

Solution 1

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))

Solution 2

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;
}

Solution 3

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.

Share:
10,907
membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on July 23, 2022

Comments

  • membersound
    membersound almost 2 years

    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?