简体   繁体   中英

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

I have a Map where the value is also a 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 ). 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. 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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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