Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Stream.mapToInt handle NullPointerExceptions?

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();
like image 868
Alexander Tukanov Avatar asked Dec 31 '22 23:12

Alexander Tukanov


2 Answers

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 nulls. It's the job of the ToIntFunction instance to decide that, and your ToIntFunction doesn't handle nulls.

like image 72
Eran Avatar answered Jan 02 '23 11:01

Eran


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();
like image 37
ETO Avatar answered Jan 02 '23 13:01

ETO