Lambda表达式使用问题记录

List 转 Map

  • 报错:
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1254)
	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: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)
  • 原因:
    java8中lambda表达式:Collectors.toMap(p1, p2),如果key重复会报这个错误
  • 解决:
    使用三个参数的方法:Collectors.toMap(p1, p2, (o1, o2) -> o2) / Collectors.toMap(p1, p2, (o1, o2) -> o1)
  • 说明:
    (o1, o2) -> o2 表示Key相同情况下,用后面的值替换前面的值,(o1, o2) -> o1 表示以前面的值为准
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页