The method Java8 Stream findAny null pointer exception (a NullPointerException) Comparative Example

Introduction combat

Stream Java8 finished learning method, it may be that you are ready to show its mettle, but found that many problems encountered, this article bring you a findAny method throws java.lang.NullPointerException scene.

Actual content

What will be printed after a look at the following code execution guess what?

public class FindAnyTest {

    @Test
    public void test() {
        List<Foo> list = new ArrayList<>();
        list.add(new Foo());

        // 方法一
        Integer id = list.stream().map(Foo::getId).findAny().orElse(null);

        System.out.println(id);
        
        // 方法二
        id = list.stream().findAny().map(Foo::getId).orElse(-1);
        System.out.println(id);
    }
}

class Foo {
    Integer id;

    public Integer getId() {
        return this.id;
    }
}

Then, unit testing method, you'll find a method throws an exception:

java.lang.NullPointerException

If you delete a method, the method is executed only two, does not appear abnormal. why?

Specific analysis

A method First, list.stream (). Map (Foo :: getId) by the map, to the original Stream was converted, to generate a new Stream, which is the value of Foo Stream id attribute defaults to null . FindAny call for an element to null Stream (), of course, the exception is thrown.

The second method, list.stream (). FindAny () is obtained Optional , And then Optional Map obtained by the method call is Optional While Optional Inside is null, then call orElse method has no problem.

Adjustment operation

If you make changes to the overall operation of the original, you can perform normal, and that is set Foo object id default value is not null, or id assigned to non-null value. Re-execution does not appear abnormal. But this is not the root of the problem, only to demonstrate results.

Original link: " Java8 method of Stream findAny null pointer exception (a NullPointerException) Comparative Example "


New Horizons program : exciting and growth are not to be missed

New Horizons program - micro-channel public number

Guess you like

Origin www.cnblogs.com/secbro/p/11685681.html