Java – NoSuchElementException when finding a match in the list
•
Java
The following old-fashioned, simple code works normally (traversing the string list and returning true because it should 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 So far, I have this:
public boolean isMatched() { List<String> stringList = Arrays.asList("str1","str3"); String matchString = "str1"; return (stringList.stream().filter(str -> StringUtils.equals(matchString,str)).findFirst().get() != null); }
Using the second method, I received the following error:
java.util.NoSuchElementException: No value present [junit] at java.util.Optional.get(Optional.java:135)
Why do I receive this error? What should I do to solve it?
Solution
Optional. Get () is used only when you know that there are actual values If there is no value, it throws nsee, as you can see
Looks like you want it findFirst(). Ispresent (), or anymatch () as described below
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码