使用 Collectors.toMap 返回 LinkedHashMap

Joh*_*xus 9 java linkedhashmap collectors

我该如何转换:

return this.subjects.entrySet()
            .stream()
            .collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()), Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)

要返回 LinkedHashMap 而不是地图?

如果您需要知道,this.subjects是一个LinkedHashMap<AbstractArtistries, ArrayList<AbstractCommand>>. AbstractArtistry 和 command 是我制作的两个自定义对象。我需要维持秩序。

getArtistryCopy() 返回 AbstractArtistry 的副本(这是关键)。

rge*_*man 14

您可使用的过载Collectors.toMap一个接受SupplierMap。它还需要一个merge函数来解决重复键之间的冲突。

return this.subjects.entrySet()
        .stream()
        .collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()), 
                                  Map.Entry::getValue,
                                  (val1, val2) -> yourMergeResultHere,
                                  LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

  • 一个简单的合并函数就是`(a, b) -&gt; b`,它覆盖了之前的值,就像是通过`Map.put`。不过,由于 OP 正在映射键,我认为他们可能应该考虑他们实际上想要对合并做什么。(我认为 `(a, b) -&gt; b)` 可能是人们默认期望的行为,[实际上 `toMap(Function, Function)` 在遇到重复键时会抛出](https://ideone. com/DP6e8E)) (2认同)