【问题标题】:Using Collectors.toMap to return a LinkedHashMap使用 Collectors.toMap 返回 LinkedHashMap
【发布时间】:2018-09-13 10:04:50
【问题描述】:

如何转换:

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

要返回 LinkedHashMap 而不是地图?

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

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

【问题讨论】:

    标签: java linkedhashmap collectors


    【解决方案1】:

    您可以使用接受Supplierthe overload of Collectors.toMap 作为Map。它还需要一个merge 函数来解决重复键之间的冲突。

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

    【讨论】:

    • 一个简单的合并函数就是(a, b) -> b,它会覆盖之前的值,就像Map.put一样。不过,由于 OP 正在映射键,我认为他们可能应该考虑他们实际上想要对合并做什么。 (我认为(a, b) -> b) 可能是人们默认的行为,when actually toMap(Function, Function) throws if it encounters a duplicate key。)
    • @Radiodef 这是合理的。对于我的回答,merge 函数只是事后的想法,因为 toMap 的唯一重载采用了 Supplier 是也采用了合并函数的重载。
    猜你喜欢
    • 2020-09-02
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多