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?
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.
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.
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.
A Boolean expression is a Java expression that returns a Boolean value: true or false .
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;
}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With