-1

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

1 回答 1

0

该陈述似乎是正确的,我认为问题在于我忘记切换 s1 和 s2。如果我切换它们,一切都会按预期工作,谢谢。

于 2016-12-16T08:41:00.670 回答