The following old-fashioned, simple code works fine (traverses a list of strings, and returns true, as there should be a match):
public boolean isMatched() {
List<String> stringList = Arrays.asList("str1", "str2", "str3");
String matchString = "str1";
for (String str : stringList) {
if (StringUtils.equals(str, matchString)) {
return true;
}
}
return false;
}
Now, I want to do the same thing, but use Java 8 instead. I have this so far:
public boolean isMatched() {
List<String> stringList = Arrays.asList("str1", "str2", "str3");
String matchString = "str1";
return (stringList.stream().filter(str -> StringUtils.equals(matchString, str)).findFirst().get() != null);
}
With this second method, I'm getting the following error:
java.util.NoSuchElementException: No value present [junit] at java.util.Optional.get(Optional.java:135)
Why am I getting this error and what should I do to solve it?
Optional.get()
is only to be used when you know there's an actual value there. If there is no value, it throws NSEE, as you've found.
It looks like you want .findFirst().isPresent()
instead, or as discussed below, anyMatch(predicate)
.
Optional.get()
throws an exception if there is no element present. It does not return null
.
If you want a way to get the element, or null
if none is present, it's orElse(null)
.
However, for your situation I would use anyMatch
:
return stringList.stream().anyMatch(matchString::equals);
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