【问题标题】:Java 8 Map fails for null values [duplicate]Java 8 Map 因空值而失败 [重复]
【发布时间】:2017-09-16 14:53:08
【问题描述】:

我正在研究 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()));

    }

}

【问题讨论】:

  • toMap 的这种行为可能应该在 Javadoc 中得到澄清。 JBS 中有一个未解决的错误:bugs.openjdk.java.net/browse/JDK-8148463
  • 作为旁注,不要盲目地使用parallelStream()。对于小型集合和/或简单任务,它会比顺序流慢得多。将单个元素映射收集到另一个映射是一项并行处理毫无意义的任务……

标签: java-8 hashmap


【解决方案1】:

但是 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();
     ...

如你所见,如果map值为null,你会得到NPE。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2012-10-16
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    相关资源
    最近更新 更多