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

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

2:如何避免,自己实现collect方法

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

3:解决方案如下

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

你可能感兴趣的:(java)