-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

どうすればこれを修正できますか?

編集

愚かな間違い: 2 番目の例で 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 に答える