No value present java ошибка

Есть поиск в коллекции:

for (Object dataRow : objects) {
    AttributeModel attribute = document.getAttributeModels().stream()
    .filter(atr -> atr.getName().equals(nameField)).findFirst().get();
....
....
}

но если элемента с таким именем нету в коллекции, вы,выбрасывает ошибку :

Exception in thread «main» java.util.NoSuchElementException: No value
present

Как правильно обработать эту ошибку в стриме?
И как можно сделать, чтобы при отсутствии элемента, выполнялся следующий цикл for() ?

Ростислав Красный's user avatar

задан 6 окт 2018 в 9:24

Леонид Дубравский's user avatar

Используйте метод Optional.get() только после проверки Optional.isPresent()

for (Object dataRow : objects) {
    Optional<AttributeModel> opt = document.getAttributeModels()
    .stream()
    .filter(atr -> atr.getName().equals(nameField))
    .findFirst();
    if (opt.isPresent()){
      AttributeModel attribute = opt.get();
    } 
....
....
}

ответ дан 6 окт 2018 в 9:31

Vlad Mamaev's user avatar

Vlad MamaevVlad Mamaev

7313 серебряных знака7 бронзовых знаков

1

In this tutorial, Learn how to fix java.util.NoSuchElementException: No value present error in java application.

This error java.util.NoSuchElementException: No value present thrown when there is no element found in Optional object with Stream API in java8.

Let’s create an array and initialize it with string values. You can check how to create and initialize an array in a single line

Let’s see a simple example to check if a string exists in an array.

It throws an error Exception in thread “main” java.util.NoSuchElementException: No value present

Let’s understand the above code.

  • Iterated an array using stream API in java8, Stream is another way to iterate the enumerated object to improve performance
  • It returns the Stream object using the stream() method
  • Calling filter method on stream which matched with a given predicate for each element and returns matched values with stream
  • Calling the first element using findFirst from the matched stream and returns Optional class
  • if optional Object is empty, get method return no value present error
    i.e Optional.get() method gives java.util.NoSuchElementException when Optional object is empty

Here is a get method implemented in java8

There are multiple ways we can fix to check for the optional object is empty or not.

Let’s see some other simple examples to reproduce and solution for this error

One way,

We can check Optional empty or not using isPresent() method in Optional class

isPresent()method returns true if value exists, else return false.

Thus, we can avoid an error.

Another way using the orElse method

The orElse method returns the default value assigned with an argument if optional is empty.
otherwise, the returns value is present in the Optional class.

Finally, you can use the orElseThrow method.

Sometimes we want to throw an error if Optional is empty, It is handy and helpful.

We can use either orElse with the default value orElseThrow method.

How to fix NoSuchElement error in java8 streams

Here is a complete example to avoid errors in the java8 stream.

It usually occurs during the streaming process with map, filter etc. methods.

We have to use orElse returns assigned default value else the return value exists in the Optional class.

Conclusion

You learned multiple ways to fix java.util.NoSuchElementException: No value present error in java8 streams.

The java.util.NoSuchElementException: No value present error occurred in spring boot application when an entity object is being attempted to get it from an optional object. If the hibernate returns an empty optional object, this exception Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.NoSuchElementException: No value present] will be thrown.The optional object should be validated before accessing the entity object in it. Otherwise, the No value present error will be thrown.

Exception

ERROR 2448 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.NoSuchElementException: No value present] with root cause
 java.util.NoSuchElementException: No value present
     at java.base/java.util.Optional.get(Unknown Source) ~[na:na]
     at com.yawintutor.BookController.findOne(BookController.java:42) ~[classes/:na]
     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
     at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
     at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:na]
     at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:na]
     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at java.base/java.lang.Thread.run(Unknown Source) [na:na]

How to reproduce this issue

From the rest controller, find an entity object that is not available in the database. Spring database repositories returns with optional class without any value. If you tries to access the object, it throws NoSuchElementException.

Root Cause

Access a element in an optional that has no value in it. Optional class throws no such element exception as no element available.

Solution 1

Add proper exception handling code around optional element in rest controller class

@GetMapping("/books/{id}")
Book findOne(@PathVariable Long id) {
    return repository.findById(id).get()
            .orElseThrow(() -> new Exception());
}

Solution 2

Add try catch block to catch and leave this exception

@GetMapping("/books/{id}")
Book findOne(@PathVariable Long id) {
 try {
    return repository.findById(id).get();
 } catch (Exception e) {
    // do nothing or add action code
 }
}

Solution 3

Check the url, path variables and parameters. validate with the database tables and identify why the data is not available in the database.

A quick strip down found out that.
This is the code that cause the error with LexicalPrinter

class InstallPluginCommand extends EnvironmentAwareCommand {

    /** Downloads a zip from the url, into a temp file under the given temp dir. */
    // pkg private for tests
    @SuppressForbidden(reason = "We use getInputStream to download plugins")
    Path downloadZip(Terminal terminal, String urlString, Path tmpDir, boolean isBatch) throws IOException {
        terminal.println(VERBOSE, "Retrieving zip from " + urlString);
        URL url = new URL(urlString);
        Path zip = Files.createTempFile(tmpDir, null, ".zip");
        URLConnection urlConnection = url.openConnection();
        urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
        try (
                InputStream in = isBatch
                        ? urlConnection.getInputStream()
                        : new TerminalProgressInputStream(urlConnection.getInputStream(), urlConnection.getContentLength(), terminal)
        ) {
            // must overwrite since creating the temp file above actually created the file
            Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
        }
        return zip;
    }



}

Remove either one or all of 2 comment lines before @Supress make setup LexicalPrinter successfully

class InstallPluginCommand extends EnvironmentAwareCommand {


    @SuppressForbidden(reason = "We use getInputStream to download plugins")
    Path downloadZip(Terminal terminal, String urlString, Path tmpDir, boolean isBatch) throws IOException {
        terminal.println(VERBOSE, "Retrieving zip from " + urlString);
        URL url = new URL(urlString);
        Path zip = Files.createTempFile(tmpDir, null, ".zip");
        URLConnection urlConnection = url.openConnection();
        urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
        try (
                InputStream in = isBatch
                        ? urlConnection.getInputStream()
                        : new TerminalProgressInputStream(urlConnection.getInputStream(), urlConnection.getContentLength(), terminal)
        ) {
            // must overwrite since creating the temp file above actually created the file
            Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
        }
        return zip;
    }



}

java.util.NoSuchElementException: No Value Present

The java.util.NoSuchElementException is a runtime exception that gets thrown when one tries to access an element that isn’t present. In the context of modern Java development, especially with the use of the Optional class introduced in Java 8, you’ll frequently see this exception in scenarios where you attempt to retrieve a value from an Optional that doesn’t have a value. 

What Triggers This Exception? 

The most common scenario for this exception to be thrown is when you use the get() method on an Optional object that is empty (i.e., it doesn’t contain a value).

Optional<String> optionalString = Optional.empty();
String value = optionalString.get(); // This will throw the exception

Understanding the Problem

The Optional class was introduced to help Java developers handle cases where a value might be absent without having to use null. Instead of returning null values and risking NullPointerExceptions, you can return an Optional that clearly signals the possibility of an absent value. 

However, care must be taken when trying to retrieve the value contained within an Optional. Simply calling get() without checking if a value is present can lead to the NoSuchElementException

How to Avoid the Exception? 

Using isPresent() Before get(): 

You can check if a value is present before trying to retrieve it.

if(optionalString.isPresent()) {
    String value = optionalString.get();
}

Using orElse(): 

Provide a default value if the Optional is empty.

String value = optionalString.orElse("Default Value");

Using orElseGet(): 

Provide a default value through a Supplier function.

String value = optionalString.orElseGet(() -> "Generated Default Value");

Using ifPresent():

Only act if a value is present.

optionalString.ifPresent(val -> System.out.println("Value is: " + val));

Avoid Using get() Directly: 

As a best practice, try not to use the get() method directly without checking for the presence of a value or providing a default value. Some even suggest that the get() method is an anti-pattern and should be avoided. 

Conclusion

The java.util.NoSuchElementException: No value present exception is a clear indication of a programming mistake when working with Optional. It’s essential to always handle the possibility of an absent value when working with Optional to prevent this runtime exception. Proper use of Optional can lead to clearer, more readable, and safer code, but misuse can introduce new types of errors, as seen with this exception.

Common Errors

Java 8

Opt

Понравилась статья? Поделить с друзьями:
  • Nmm a problem occurred during install ошибка
  • No graphic memory nier automata ошибка
  • No suitable driver found for jdbc ошибка
  • Nonce too low ошибка транзакции что это
  • No enum constant ошибка