Vous pouvez essayer ceci:
HashMap<Integer, String> original = new HashMap<>();
HashMap<String, ArrayList<Integer>> inverted = new HashMap<>();
original.put(1, "A");
original.put(2, "B");
original.put(3, "C");
original.put(4, "A");
for (Integer key: original.keySet()) {
String newKey = original.get(key);
inverted.computeIfAbsent(newKey, k -> new ArrayList<>());
inverted.get(newKey).add(key);
}
System.out.println(original);
System.out.println(inverted);
Alors, disons que HashMap<Integer, String> original
est {1=A, 2=B, 3=C, 4=A}
, alors vous obtiendrez {A=[1, 4], B=[2], C=[3]}
.
EDIT: Si vous voulez une version plus générique, comme @ Mr.Polywhirl a suggéré, vous pouvez utiliser:
public static final <T, U> Map<U, List<T>> invertMap(Map<T, U> map) {
HashMap<U, List<T>> invertedMap = new HashMap<>();
for (T key : map.keySet()) {
U newKey = map.get(key);
invertedMap.computeIfAbsent(newKey, k -> new ArrayList<>());
invertedMap.get(newKey).add(key);
}
return invertedMap;
}
de parcourir la carte existante? – BevynQ
http://stackoverflow.com/questions/3678601/how-to-do-map-inversion-with-guava-with-non-unique-values –
Ouais je pense que j'ai besoin de répéter une fois et obtenir des clés ou des valeurs à moins. – Anderson