将值从 Map<K, V<List>> 传输到 Map<otherKey, otherValue<List>> 的最佳方式

Optimal way to transfer values from a Map<K, V<List>> to a Map<otherKey, otherValue<List>>

这是我要处理的内容: Map<Faction, List<Resource>>

所以列表现在看起来像这样:

("rr", "wool")
("rr", "wool")
("rr", "lumber")
("bb", "wool")

所以我的目标是Map<Resource, Integer>

目标包含的值示例:("Wool", 4), ("Grain", 3), ("Lumber", 2)


所以我正在尝试这样做(在伪代码中):


我玩过流和 foreach 循环,但还没有生成任何有价值的代码,因为我在概念阶段还很挣扎。

Map<Faction, List<Resource>> 中的实际输入数据看起来像:

{rr=[wool, wool, lumber], bb=[lumber, wool, grain]}

假设为 ResourceFaction 使用了适当的枚举,可以使用 flatMap 为输入映射中的值检索资源与其数量的映射:

Map<Faction, List<Resource>> input; // some input data

Map<Resource, Integer> result = input
    .values() // Collection<List<Resource>>
    .stream() // Stream<List<Resource>>
    .flatMap(List::stream) // Stream<Resource>
    .collect(Collectors.groupingBy(
        resource -> resource,
        LinkedHashMap::new, // optional map supplier to keep insertion order
        Collectors.summingInt(resource -> 1)
    ));

Collectors.toMap可能适用:

...
    .collect(Collectors.toMap(
        resource -> resource,
        resource -> 1,
        Integer::sum,      // merge function to summarize amounts
        LinkedHashMap::new // optional map supplier to keep insertion order
    ));