Exception in thread “main” java.lang.NullPointerException
at java.util.HashMap.merge(HashMap.java:1225)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1384)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.ex.demo2.user.Test.main(Test.java:25)

@Data
public class Product {
    private Integer id;
    private String name;
    private String sex;
}

public class Test {
    public static void main(String[] args) {
        List<Product> products = new ArrayList<Product>();
        for (int i = 0; i < 3; i++) {
            Product product = new Product();
            product.setId(i + 1);
            product.setName(String.format("name_%s", i));
            product.setSex(i % 2 == 0 ? "MAN" : "WOMAN");
            products.add(product);
        }
//这里把第二个product的name设为null
        products.get(1).setName(null);
        Map<Integer, String> collect = products.stream().collect(Collectors.toMap(Product::getId,Product::getName));
        System.out.println(collect);
}

这里可以看到如果toMap的value是null的就会报空指针,经过测试 如果id为null也会报空指针

解决这个问题,可以通过filter过滤掉这些null的数据

     Map<Integer, String> collect = products.stream()
                .filter(k -> k.getId() != null).filter(v -> v.getName() != null)
.collect(Collectors.toMap(Product::getId, Product::getName));