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
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 "