2017-04-20 65 views
0

我正在使用Java8,发现收集器失败时,我在hashmap中使用null。Java 8映射失败为空值

我得到空指针异常。我的查询是如果哈希映射允许空值,那么为什么我在这里得到空指针。

public class Test { 

    public static void main(String[] args) { 
     HashMap<String, String> m = new HashMap<>(); 
     m.put("abc", null); 

     m.entrySet().parallelStream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); 

    } 

} 
+1

'toMap'的这种行为应该可能在Javadoc中得到澄清。在JBS中有一个开放的bug:https://bugs.openjdk.java.net/browse/JDK-8148463 –

+1

正如一个附注,不要盲目地使用'parallelStream()'。对于小集合和/或简单任务,它将比顺序流慢得多。并且将单个元素地图收集到另一个地图中是这样的任务,其中并行处理没有意义... – Holger

回答

2

但Collectors.toMap(以下利斯特):

public static <T, K, U, M extends Map<K, U>> 
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, 
          Function<? super T, ? extends U> valueMapper, 
          BinaryOperator<U> mergeFunction, 
          Supplier<M> mapSupplier) { 
    BiConsumer<M, T> accumulator 
      = (map, element) -> map.merge(keyMapper.apply(element), 
              valueMapper.apply(element), mergeFunction); 
    return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID); 
} 

使用合并方法:

@Override 
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(); 
    ... 

正如你可以看到,如果地图值为空,你会得到NPE。