Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchElementException when looking for a match in a List

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?

like image 471
cvoep28 Avatar asked Jan 07 '23 08:01

cvoep28


2 Answers

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

like image 148
Louis Wasserman Avatar answered Jan 08 '23 22:01

Louis Wasserman


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);
like image 20
Paul Boddington Avatar answered Jan 08 '23 22:01

Paul Boddington