Multiple ways to fix java.util.NoSuchElementException in java
- Admin
- Mar 10, 2024
- Java-examples
In this tutorial, Learn the solution for java.util.NoSuchElementException: No value present error in the Java application.
What is java.util.NoSuchElementException error?
This error java.util.NoSuchElementException: No value present
thrown when there is no element found in the Optional
object with Stream API usage 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 types in java8 to improve performance.
- It returns the
Stream
object using thestream()
method - Calling the
filter
method on stream, which checks the predicate for each element, and returns a matched stream of values. - Calling the first element using
findFirst
from the matched stream and returns Optional class - if the
optional
Object is empty, theget
method returns ano value present
error i.e.Optional.get()
method gives java.util.NoSuchElementException when the 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 whether the optional object is empty or not.
Let’s see some other simple examples to reproduce, and a 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 if Optional is empty or not using the isPresent()
method in Optional class.
if (number2.isPresent()){
System.out.println(number2.get());
}else{
System.out.println("number2 is an empty");
}
The isPresent()
method returns true
, if a value exists, else return false
. with this approach, we can fix the 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 the orElse
returns assigned a 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.