我已阅读主题:
但我不明白如何将它应用于我的问题:
我的代码:
Map<String, List<MappingEntry>> mappingEntryMap = mapping.getMappingEntries()
.stream()
.collect(Collectors.groupingBy(MappingEntry::getMilestone, Collectors.mapping(e -> e, Collectors.toList())));
对我来说,MappingEntry::getMilestone
有时可能返回空值。虽然这对我的情况没有问题,但我还是想指出:
Caused by: java.lang.NullPointerException: element cannot be mapped to a null key
at java.util.Objects.requireNonNull(Objects.java:228)
at java.util.stream.Collectors.lambda$groupingBy$45(Collectors.java:907)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
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)
我该如何避免这个异常?
Collectors.mapping(e -> e, Collectors.toList())
可以简化为Collectors.toList()
。 - LinoCollectors.groupingBy
时,可以省略Collectors.toList()
。 - Holger