I keep on getting 'java.util.NoSuchElementException: No value present' when executing filter findFirst. I can't change the code much as it will break other part of code and we dont want to write method logic inside filter. Code give is below.
--- I am getting below error when calling the method
Error :
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
The error is because the value is null for " .filter(x -> x > 5) .findFirst()"
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
// .peek(num -> System.out.println("will filter " + num))
.filter(x -> x== null)
.map( t -> {
System.out.println("hello");
return 0;
})
.filter(x -> x > 5)
.findFirst()
.get();
System.out.println(a);
Here list.stream() will give stream which will be use by .filter(x -> x== null). Now in this scenario x is not null so when it come to .filter(x -> x > 5) it give null because stream is not there. Hence the exception.
I need help in some alternative for this.