[英]Retrieve all relevant values from a nested HashMap with the same outermap key
我有一個Map,其中的值也是Map:
HashMap<String, Map<String, Integer>> map;
我已經填充它,以便值是這樣的:
"Red"="Apple",10
"Red"="Cherry",5
"Red"="Strawberry",7
"Yellow"="Banana",12
"Orange"="Orange",9
我基本上希望能夠傳遞Red
並檢索嵌套地圖的所有相關鍵( Apple
, Cherry
, Strawberry
)。 當我使用以下代碼時,似乎只返回一個值而不是全部:
public class Groceries {
private HashMap<String, Map<String, Integer>> groceries;
public Groceries() {
groceries = new HashMap<>();
}
public Set<String> getFruitsGivenColor(String color) {
Set<String> fruits = new HashSet<>();
HashMap<String, Integer> map = groceries.get(origin);
for (HashMap.Entry<String,Integer> entry : map.entrySet()) {
fruits.add(entry.getKey());
}
return fruits;
}
}
任何幫助是極大的贊賞
您不能只獲取嵌套地圖的鍵嗎?
String key = "Red";
Set<String> keys = groceries.get(key).keySet(); //this is what you want
同樣,聽起來您可能會在映射中put
幾對,每對都有相同的鍵,因此將覆蓋先前的put
調用,從而產生總共一個元素。 如果您正在執行以下操作:
map.put("Red", appleMap);
map.put("Red", cherryMap);
map.put("Red", strawberryMap);
您應該改為:
map.put("Red", appleMap);
for (String key : cherryMap)
{
map.get("Red").put(cherryMap.get("Red"));
}
for (String key : strawberryMap)
{
map.get("Red").put(strawberryMap("Red"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.