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 a nd initialize with string values. You can check how to create and initialize an array in a single line

Let’s see an simple example to check an 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 Stream object using stream() method
  • Calling filter method on stream which matched with given predicate for each element and returns matched values with stream
  • Calling 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 an 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 optional object is empty or not

Let’s see some other simple example 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.

This we can avoid an error.

Another way using orElse method

orElse method returns default value which assigned with an argument if optional is empty. otherwise, returns value present in 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 orElseThrow method

Some times we want to thrown an error if Optional is empty, This 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 default value orElseThrow method

How to fix NoSuchElement error in java8 streams

Here is an complete example to avoid error in java8 stream.

This usually occurs during stream process with map, filter etc. methods.

We have to use orElse returns assigned default value else return value exist in 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.