【发布时间】:2019-07-02 19:43:22
【问题描述】:
我想创建一个 BiFunction 对象 (Lambda),并在 Map 的计算方法中使用它。它会正确编译,但会在运行时抛出 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);
【问题讨论】:
-
你确定
model == null不应该是quantity == null吗? -
谢谢,你是对的。改成quantity == null,就成功了。
-
但是使用
hashmap.merge(i, 1, Integer::sum);更简单,相当于hashmap.merge(i, 1, (a, b) -> a + b);,所以不需要处理null。 -
@Holger,谢谢!帮帮我!
标签: java function java-8 hashmap