地图计算方法中的双函数对象



我想创建一个双方函数对象(lambda(,然后在地图的计算方法中使用它。它将正确编译,但会在运行时投掷NullPoInterException。

private BiFunction<String, Integer, Integer> biFunctionWithAddition(final Integer addition) {
        return (model, quantity) -> model == null ? addition : quantity + addition;
    }
hashmap.compute(i, biFunctionWithAddition(1)) //throw NullPointerException

//the one that can work should be:
hashmap.compute(i, (num, quantity) -> num == null : 1 ? quantity + 1);

Compute方法也被调用,如果密钥不在地图中,则可以为密钥创建值。因此,在您的情况下,发生这种情况:

hashmap.compute("KEY_NOT_IN_MAP", biFunctionWithAddition(1));

会以这样的方式调用您的lambda功能:

("KEY_NOT_IN_MAP",null) ->KEY_NOT_IN_MAP" == null ? addition : null + addition;

因此,您可以看到键(模型(不是零的,因此将评估三元运算符的第二部分,并因此将使用NPE失败:null + addition;

您在lambda中的数量为null。

最新更新