Java8使用Collectors.toMap,当value为null时报空指针异常

Collectors.toMap()方法底层调用merge方法,会报空指针异常。

public static >
    Collector toMap(Function keyMapper,
                                Function valueMapper,
                                BinaryOperator mergeFunction,
                                Supplier mapSupplier) {
        BiConsumer accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }

解决方式,自己实现collect方法

 R collect(Supplier supplier,
                  BiConsumer accumulator,
                  BiConsumer combiner);

 如下:

params.stream().collect(HashMap::new, (m, v) -> m.put(v.getId(), v.getOther()), HashMap::putAll);

 

你可能感兴趣的:(java)