0

I was working on Java8 and found collector is failing when i use null in hashmap.

I am getting null pointer exception . My query is if hash map allows null values then why i am getting null pointer here.

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

    }

}
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 1
    This behavior of `toMap` should probably have ben clarified in the Javadoc. There is an open bug in JBS: https://bugs.openjdk.java.net/browse/JDK-8148463 – Stefan Zobel Apr 20 '17 at 08:45
  • 1
    Just as a side note, don’t use `parallelStream()` mindlessly. For small collections and/or simple tasks, it will be much slower than a sequential stream. And collecting a single element map into another map is such a task where parallel processing makes no sense… – Holger Apr 20 '17 at 15:22

1 Answers1

2

But Collectors.toMap (lister below):

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

uses merge method:

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

As you can see if map value is null, you will get NPE.

Beri
  • 11,470
  • 4
  • 35
  • 57