Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
membersound Avatar asked Dec 09 '15 08:12

membersound


People also ask

How do you return a Boolean object in Java?

The equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.

How do I return a Boolean in Java 8?

The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true" . Example: Boolean. parseBoolean("True") returns true . Example: Boolean.

Which stream API methods used to evaluate Boolean conditions and return the result?

match() Various matching operations can be used to check whether a given predicate matches the stream elements. All of these matching operations are terminal and return a boolean result.

What is the return type of Boolean in Java?

A Boolean expression is a Java expression that returns a Boolean value: true or false .


2 Answers

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;
}
like image 139
Tagir Valeev Avatar answered Oct 18 '22 20:10

Tagir Valeev


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))
like image 26
Bohemian Avatar answered Oct 18 '22 20:10

Bohemian