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);
答案 0 :(得分:2)
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))
)