使用 SimpleEntry 和 StreamEx 创建地图

Create a Map with SimpleEntry and StreamEx

我看到了一个 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));

这个说法似乎是正确的,我认为问题是我忘记切换s1和s2了。如果我切换它们,一切都会按预期工作,谢谢。