This code will give NullPointerException. Isn't the mapToInt (map) method supposed to handle NPE?
List<Integer> list = Arrays.asList(null, null);
OptionalDouble op = list.stream()
.mapToInt(val->val)
.average();
Why do you expect it to handle NullPointerException
?
The lambda expression val->val
is equivalent to:
new ToIntFunction<Integer> () {
int applyAsInt(Integer value) {
return value;
}
}
And when a method that has an int
return type returns an Integer
, auto-unboxing takes place. This means value.intValue()
is called, and if value
is null
, NullPointerException
is thrown.
mapToInt()
simply calls the applyAsInt()
method of the ToIntFunction
instance passed to it for each element of the Stream
.
It has no reason to check that an element is null
and somehow handle it, since it has no way of knowing how you wish to deal with null
s. It's the job of the ToIntFunction
instance to decide that, and your ToIntFunction
doesn't handle null
s.
As Eran has already noted in his answer, the mapToInt
is not supposed to handle NPE.
You have to deal with it instead, by providing your custom null-check logic. E.g.:
OptionalDouble op = list.stream()
.mapToInt(val -> val == null ? 0 : val)
.average();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With