這是我必須使用的: Map<Faction, List<Resource>>
所以列表現在看起來像這樣:
("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
and 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
));
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen