Java 8 Collectors.toMap SortedMap

后端 未结 5 666
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 02:28

I\'m using Java 8 lambdas and want to use Collectors toMap to return a SortedMap. The best I can come up with is to call the following

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 03:00

    I don't think you can get much better than this:

    .collect(Collectors.toMap(keyMapper, valueMapper,
                            (v1,v2) ->{ throw new RuntimeException(String.format("Duplicate key for values %s and %s", v1, v2));},
                            TreeMap::new));
    

    where the throw lambda is the same as throwingMerger() but I can't directly call that since it's package private (you can of course always make your own static method for that like throwingMerger() is. )

提交回复
热议问题