2017-04-20 66 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。