How to swap arrayMap values and keys in Java

前端 未结 4 670
孤独总比滥情好
孤独总比滥情好 2021-01-15 06:04

I\'m having a bit of trouble reversing a given map and storing its reversed keys and values into another map. I have a method prototype as follows:

public st         


        
4条回答
  •  别那么骄傲
    2021-01-15 06:48

    You will need to loop over the entries in your map, and then, since the values are stored in a set, you will need to loop over that set. You will need to check your result map for each key and create a new set whenever a key does not yet exist.

    public static Map> reverse (Map > graph) {
        Map> result = new HashMap>();
        for (Map.Entry> graphEntry: graph.entrySet()) {
            for (String graphValue: graphEntry.getValue()) {
                Set set = result.get(graphValue);
                if (set == null) {
                    set = new HashSet();
                    result.put(graphValue, set);
                }
                set.add(graphEntry.getKey());
            }
        }
        return result;
    }
    

提交回复
热议问题