Multiple ways to fix java.util.NoSuchElementException: No value present error in java

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.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> srs = new ArrayList<>(Arrays.asList("One", "two", "three"));
        String str=srs.stream().filter(e->e.equals("ten")).findFirst().get();


    }
}

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

Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at Test.main(Test.java:8)

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

 public T get() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

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

Optional<Integer> number1  =  Optional.of(123);
Optional<Integer> number2  =  Optional.empty();
System.out.println(number1.get()); // 123
System.out.println(number2.get()); // Exception in thread "main" java.util.NoSuchElementException: No value present

One way,

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

        if (number2.isPresent()){
            System.out.println(number2.get());
    }else{
            System.out.println("number2 is an empty");
        }

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.

Optional<Integer> number1 = Optional.of(123);
System.out.println(number1.orElse(0)); // 123
Optional<Integer> number2 = Optional.empty();
System.out.println(number2.orElse(0));

Finally, you can use the orElseThrow method.

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

        Optional<Integer> number1 = Optional.of(123);
        System.out.println(number1.orElse(0)); // 123
        Optional<Integer> number2 = Optional.empty();
        System.out.println(number2.orElseThrow(Exception::new));

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.

import java.util.List;
import java.util.Optional;

public class Test {
    public static void main(String[] args)  throws Exception{
        List<String> srs = new ArrayList<>(Arrays.asList("one", "two", "three"));
        String result=srs.stream().filter(e->e.equals("ten")).findFirst().orElse("");
        System.out.println(result);
        String result1=srs.stream().filter(e->e.equals("one")).findFirst().orElse("");
        System.out.println(result1);

    }
}

Conclusion

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