Java 8 Java 8映射对于空值失败
我当时正在处理Java8,当我在hashmap中使用null时发现收集器失败 我得到空指针异常。我的问题是,如果哈希映射允许空值,那么为什么我在这里得到空指针Java 8 Java 8映射对于空值失败,java-8,hashmap,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.
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()));
}
}
公共类测试{
公共静态void main(字符串[]args){
HashMap m=新的HashMap();
m、 put(“abc”,空);
m、 entrySet().parallelStream().collect(Collectors.toMap(e->e.getKey(),e->e.getValue());
}
}
但是Collectors.toMap(下面的列表):
公共静态
收集器toMap(函数但Collectors.toMap(下面的列表器):
公共静态
收集器toMap(function)toMap
的这种行为应该在Javadoc中得到澄清。JBS中有一个公开的bug:作为旁注,不要使用parallelStream()
无意识地。对于小集合和/或简单任务,它将比顺序流慢得多。而将单个元素映射收集到另一个映射是这样一个任务,并行处理毫无意义……这种toMap
的行为可能应该在Javadoc中得到澄清。JBS中存在一个开放的错误:就像请注意,不要无意识地使用parallelStream()
。对于小集合和/或简单任务,它将比顺序流慢得多。而将单个元素映射收集到另一个映射是这样一个任务,并行处理毫无意义…
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();
...