这是使用Guava Multimaps的实际、有效、最新的代码:
SetMultimap<Integer, Integer> graph = HashMultimap.create();
graph.put(1, 2); // add an edge from 1 to 2
SetMultimap<Integer, Integer> inverse = Multimaps.invertFrom(
graph, HashMultimap.<Integer, Integer> create());
(披露:我为 Guava 做出了贡献。)
但是,如果您不能使用第三方库,请执行以下操作...
Map<Integer, Set<Integer>> g;
Map<Integer, Set<Integer>> gInverse = new HashMap<Integer, Set<Integer>>();
for (Map.Entry<Integer, Set<Integer>> gAdj : g.entrySet()) {
Integer v = gAdj.getKey();
for (Integer w : gAdj.getValue()) {
Set<Integer> wInverseAdj = gInverse.get(w);
if (wInverseAdj == null) {
gInverse.put(w, wInverseAdj = new HashSet<Integer>());
}
wInverseAdj.add(v);
}
}
或者,如果您可以使用 Java 8,请使用此...
map.entrySet().stream()
.flatMap(entryKToVs -> entryKToVs.getValue().stream()
.map(v -> new AbstractMap.SimpleEntry<>(entryKToVs.getKey(), str)))
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toList())))