Getting NoSuchElementException when doing filter findFirst

1.3k Views Asked by At

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.

1

There are 1 best solutions below

3
Sean Van Gorder On

This will print 10 as expected, or "Null" if the list is empty:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
Optional<Integer> a = list.stream()
        .filter(x -> x > 5)
        .findFirst();
System.out.println(a.isPresent() ? a.get() : "Null");

You don't want to use the map method here, that's used to apply an operation to each element and replace it with the result. For example, .map(x -> x + 3) would change [1, 10, 3, 7, 5] into [4, 13, 6, 10, 8]. You can't tell whether the stream is empty or not from an intermediate operation like map, you need to use a terminal operation like findFirst and look at the result.