gpt4 book ai didi

java-8 - 当 toMap 存储空值时,java 流抛出 NPE

转载 作者:行者123 更新时间:2023-12-04 03:12:52 24 4
gpt4 key购买 nike

HashMap 允许存储 NULL 值,但是 Stream.toMap(r-> r.getName(), r->r.get(obj) ) 会在 r.get(obj) 返回 null 时抛出 NPE?我是否漏掉了什么,或者 Stream 有比 Map 更小心的特殊原因?我正在尝试使用反射和 java8 来实现 (new ObjectMapper()).convertValue(obj, Obj.class);

最佳答案

Collector.toMap使用 HashMap::merge合并结果:

public V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if (value == null)
throw new NullPointerException();
if (remappingFunction == null)
throw new NullPointerException();

因此它可能存储空值,但合并不允许它。

你可以通过使用 forEach 来变通

stream.forEach (
r-> map.put(r.getName(), r.get(obj))
)

关于java-8 - 当 toMap 存储空值时,java 流抛出 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43606886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com