当toMap存储空值时,java stream会抛出NPE [英] java stream throws NPE when toMap stores a null value

查看:660
本文介绍了当toMap存储空值时,java stream会抛出NPE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashMap 允许存储 NULL 值,但 Stream.toMap(r-> ;当 r.get(obj)返回null时,r.getName(),r-> r.get(obj))将抛出NPE ?我错过了什么或 Stream 有一个特殊的理由比 Map 更小心吗?我正在尝试使用反射和java8来实现(new ObjectMapper())。convertValue(obj,Obj.class);

HashMap allows to store NULL value, but Stream.toMap(r-> r.getName(), r->r.get(obj)) would throw NPE when r.get(obj) returns null? Do I miss something or Stream has a special reason to be more careful than Map? I am trying to use reflection and java8 to achieve (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();

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

So it may store null values, but merge does not allow it.

你可以通过使用forEach

You can do a work around, by using forEach

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

这篇关于当toMap存储空值时,java stream会抛出NPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆