我想建立一個基于 2 個陣列的地圖,其中 1 個鍵里面有很多物件。
鍵:“字母 A” 值:“信天翁” 值:“鱷魚”
鍵:“字母 B” 值:“獾” 值:“Bandicoot”
結構必須顯示關鍵 1 次,不重復
uj5u.com熱心網友回復:
希望代碼是不言自明的。
爪哇 7:
public Map<String, List<String>> group(String[] input) {
Map<String, List<String>> result = new HashMap<>();
for (String str : input) {
String key = "Letter " str.charAt(0);
if (result.containsKey(key)) {
result.get(key).add(str);//if Key already exists, just add this word to existing list.
} else {
List<String> list = new ArrayList<>();
list.add(str);
result.put(key, list); //Otherwise, create a new list and add the new word into the list
}
}
return result;
}
爪哇 8:
public static Map<String, List<String>> group(String[] input) {
return Arrays.stream(input)
.collect(Collectors.groupingBy(k -> "Letter " k.charAt(0)));
//Provide the key for how you want to group. In your case it is first character of string.
}
uj5u.com熱心網友回復:
您可以使用 Guava 的 Mutlimap 實作,但它可能與 Java 7 不兼容。https://guava.dev/releases/23.0/api/docs/com/google/common/collect/Multimap.html
您可以通過對地圖中的值使用 List 來獲得相同的效果,如下所示:
Map<String, List<String>> map = new HashMap<>();
然后,假設對于您要添加到地圖中的每個條目,您有 key inkey和 value in val,像這樣添加它:
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
map.put(key, list);
}
list.add(val);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/444345.html
上一篇:正則運算式不匹配
