当使用jdk8的 stream() .collect(Collectors.toMap()时value为空会报null指针异常

1.当使用jdk8的 stream() .collect(Collectors.toMap()时value为空会报null指针异常。
Map dataMap = JSONObject.parseObject(cfg.getData(), new TypeReference>() {
});
Map resultData = new LinkedHashMap<>();


resultData = variableNames.stream()
                          .collect(Collectors.toMap(x -> x,
                                                    x -> dataMap.getOrDefault(x, null),
                                                    (x, y) -> y,
                                                    LinkedHashMap::new));

result.add(resultData);

 

- ApiController.configData: exception fail
java.lang.NullPointerException: null
    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:1382)
    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)

主要hashmap 的merge方法加了判null 直接抛异常

当使用jdk8的 stream() .collect(Collectors.toMap()时value为空会报null指针异常_第1张图片
解决办法 :

1.

// for (String variableName : variableNames) {
//     // if (!dataMap.containsKey(variableName) || Objects.isNull(dataMap.get(variableName))) {
//     //     continue;
//     // }
//     Object value = dataMap.getOrDefault(variableName, null);
//     resultData.put(variableName, value);
// }

2.可以参考:

https://blog.csdn.net/qq_31086797/article/details/106649290

你可能感兴趣的:(java后台)