Reputation: 4797
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);
Upvotes: 3
Views: 4054
Reputation: 11620
Collector.toMap uses HashMap::merge to combine results:
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.
You can do a work around, by using forEach
stream.forEach (
r-> map.put(r.getName(), r.get(obj))
)
Upvotes: 2