Search code examples
java-8collectors

HashMap null check in Merge Operation


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


Solution

  • 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);