【发布时间】:2016-12-14 09:31:37
【问题描述】:
我看到了一个 StreamEx 的例子,它非常好,就像这样
Map<String, String> toMap = StreamEx.of(splittedTimeUnit1)
.pairMap((s1, s2) -> s1.matches("-?\\d+(\\.\\d+)?") ? new String[]{s2, s1} : null)
.nonNull()
.toMap(a -> a[0], a -> a[1]);
这很好用,我的输出是{seconds=1, minutes=1},没关系。不完美,因为我必须稍后转换数字。
我尝试使用SimpleEntry<String,Integer>进行优化:
Map<String, String> toMap2 = StreamEx.of(splittedTimeUnit1)
.pairMap((s1, s2) -> s1.matches("-?\\d+(\\.\\d+)?") ? new SimpleEntry<>(s1,s2) : null)
.nonNull()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
编译但现在我遇到了问题,一些值被多次放入映射中,导致Exception in thread "main" java.lang.IllegalStateException: Duplicate key minutes
我该如何解决这个问题?
编辑
愚蠢的错误:我忘了在第二个例子中切换 s1 和 s2
Map<String, String> toMap2 = StreamEx.of(splittedTimeUnit1)
.pairMap((s1, s2) -> s1.matches("-?\\d+(\\.\\d+)?") ? new SimpleEntry<>(s2,s1) : null)
.nonNull()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
【问题讨论】:
-
您没有进行任何字符串到数字的转换。你刚刚交换了键和值——为什么?
-
是的,我认为这是第二个的问题。如果我切换它们,一切都会按预期工作,谢谢。我想将单位作为键,将数字作为值,所以这是故意的
标签: java java-8 java-stream streamex