Java 8映射因空值而失败

时间:2017-04-20 06:15:38

标签: java-8 hashmap

我正在研究Java8,发现当我在hashmap中使用null时收集器失败。

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

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 个答案:

答案 0 :(得分: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。