合并操作中的HashMap

合并操作中的HashMap

本文介绍了合并操作中的HashMap null检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么HashMap合并正在对值进行空值检查。 HashMap支持null键和null值。所以可以告诉我为什么需要对合并进行null检查?

  @Override 
public V merge(K key,V value,
BiFunction<?super V,?super V,?extends V> remappingFunction){
if(value == null)
throw new空指针异常();
if(remappingFunction == null)
抛出新的NullPointerException();

由于这个原因,我无法使用 Collectors.toMap(Function.identity) (),this :: get)收集地图中的值

解决方案

因为内部用于 Collectors.toMap 使用Map#merge - 你无法真正做任何事情它。使用静态 Collectors.toMap 不是一个选项(顺便提一下,它会抛出 NullPointerException )。 / p>

但是,旋转自定义收集器以便能够做你想要的(你没有显示)并不复杂,这是一个例子:

  Map< Integer,Integer> result = Arrays.asList(null,1,2,3)
.stream()
.collect(
HashMap :: new,
(map,i) - > {
map.put(i,i);
},
HashMap :: putAll);


Why HashMap merge is doing null check on value. HashMap supports null key and null values.So can some one please tell why null check on merge is required?

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

Due to this I am unable to use Collectors.toMap(Function.identity(), this::get) to collect values in a Map

解决方案

Because internally for Collectors.toMap, Map#merge is used - you can't really do anything about it. Using the static Collectors.toMap is not an option (which by the way is documented to throw a NullPointerException).

But spinning a custom collector to be able to do what you want (which you have not shown) is not that complicated, here is an example:

 Map<Integer, Integer> result = Arrays.asList(null, 1, 2, 3)
            .stream()
            .collect(
                    HashMap::new,
                    (map, i) -> {
                        map.put(i, i);
                    },
                    HashMap::putAll);

这篇关于合并操作中的HashMap null检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:20