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 static Map> reverse (Map > graph);
So if I have sample keys for the directed graph such that:
{c -> arraySet{f, e}}
{b -> d}
{a -> arraySet{c, b}}
{d -> g}
{e -> d}
{f -> arraySet{g, d}}
I need to effectively reverse this graph so that instead of b -> d I have d -> b.
I think all this requires is for me is to interchange the values and keys in the original graph and add them to the reverseMap. I suppose I could iterate through each set of values for a given key in the graph and then and store those in a list.
Unfortunately, I'm having trouble implementing this and thinking it through. I'd really appreciate a nudge in the right direction.
解决方案
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;
}