简体   繁体   English

使用相同的externalmap键从嵌套HashMap中检索所有相关值

[英]Retrieve all relevant values from a nested HashMap with the same outermap key

I have a Map where the value is also a Map: 我有一个Map,其中的值也是Map:

HashMap<String, Map<String, Integer>> map;

I have populated it so that the values are something like: 我已经填充它,以便值是这样的:

"Red"="Apple",10
"Red"="Cherry",5
"Red"="Strawberry",7
"Yellow"="Banana",12
"Orange"="Orange",9

I basically want to be able to pass in Red and retrieve all the relevant keys of the nested map ( Apple , Cherry , Strawberry ). 我基本上希望能够传递Red并检索嵌套地图的所有相关键( AppleCherryStrawberry )。 When I use the following code it seems to only return one value instead of all: 当我使用以下代码时,似乎只返回一个值而不是全部:

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;
    }
}

Any help is greatly appreciated 任何帮助是极大的赞赏

Can't you just get the keys of the nested map? 您不能只获取嵌套地图的键吗?

String key = "Red";
Set<String> keys = groceries.get(key).keySet();   //this is what you want

Also, it sounds like you may be put ting several pairs into the map with the same key for each, and thus are overriding the previous put calls, yielding a total of one element. 同样,听起来您可能会在映射中put几对,每对都有相同的键,因此将覆盖先前的put调用,从而产生总共一个元素。 If you are doing something like: 如果您正在执行以下操作:

map.put("Red", appleMap);
map.put("Red", cherryMap);
map.put("Red", strawberryMap);

You should be instead doing: 您应该改为:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM