When using java8 stream API
.stream().map(mapper)
is it neccessary in the mapper's apply(T t)
method implemented as java.util.function.Function<T,R>
check for null
input t
? Or is it guaranteed that the apply(T t)
method is never called with null
argument even when my stream()
-ed Collection
contains null
s?
In another words,
.stream().map(mapper)
allows null
values to be passed into apply(T t)
and does not throws NullPointerException
?
It depends on whether you expect a null
as an input. In general you will want to avoid using null
is a stream (or throwing check exceptions). You can do
list.stream()
.filter(x -> x != null)
.... do more
Note if you do
Stream.of("hi", null).forEach(System.out::println);
will print
hi
null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.