将值从 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”代表红队,“bb”代表蓝队)
- Resources 是资源的字符串枚举值,例如“Wool”、“Lumber”
所以列表现在看起来像这样:
("rr", "wool")
("rr", "wool")
("rr", "lumber")
("bb", "wool")
所以我的目标是Map<Resource, Integer>
- 其中资源是枚举中资源的字符串名称
- 整数代表资源卡数量
目标包含的值示例:("Wool", 4), ("Grain", 3), ("Lumber", 2)
所以我正在尝试这样做(在伪代码中):
- 提取属于
Faction
“rr”的所有资源并将它们放入映射<Resources, Integer>
中,其中每种资源类型应表示一次,Integer
表示数量的总和Resource
张卡片
--> 为另外 3 个玩家重复此步骤 Faction
我玩过流和 foreach 循环,但还没有生成任何有价值的代码,因为我在概念阶段还很挣扎。
Map<Faction, List<Resource>>
中的实际输入数据看起来像:
{rr=[wool, wool, lumber], bb=[lumber, wool, grain]}
假设为 Resource
和 Faction
使用了适当的枚举,可以使用 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
));
这是我要处理的内容:
Map<Faction, List<Resource>>
- 派系是玩家派系的枚举字符串值(例如,“rr”代表红队,“bb”代表蓝队)
- Resources 是资源的字符串枚举值,例如“Wool”、“Lumber”
所以列表现在看起来像这样:
("rr", "wool")
("rr", "wool")
("rr", "lumber")
("bb", "wool")
所以我的目标是Map<Resource, Integer>
- 其中资源是枚举中资源的字符串名称
- 整数代表资源卡数量
目标包含的值示例:("Wool", 4), ("Grain", 3), ("Lumber", 2)
所以我正在尝试这样做(在伪代码中):
- 提取属于
Faction
“rr”的所有资源并将它们放入映射<Resources, Integer>
中,其中每种资源类型应表示一次,Integer
表示数量的总和Resource
张卡片 --> 为另外 3 个玩家重复此步骤Faction
我玩过流和 foreach 循环,但还没有生成任何有价值的代码,因为我在概念阶段还很挣扎。
Map<Faction, List<Resource>>
中的实际输入数据看起来像:
{rr=[wool, wool, lumber], bb=[lumber, wool, grain]}
假设为 Resource
和 Faction
使用了适当的枚举,可以使用 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
));