Obwohl dies die Frage nicht direkt beantwortet, ist es verwandt.
Auf diese Weise müssen Sie nicht ständig erstellen/iterieren. Erstellen Sie einfach einmal eine Umkehrabbildung und holen Sie sich, was Sie benötigen.
/**
* Sowohl Schlüssel als auch Werttypen müssen equals() und hashCode() definieren, damit dies funktioniert.
* Hierbei wird berücksichtigt, dass alle Schlüssel eindeutig sind, aber nicht alle Werte.
*
* @param map
* @param
* @param
* @return
*/
public static Map> reverseMap(Map map) {
if(map == null) return null;
Map> reverseMap = new ArrayMap<>();
for(Map.Entry entry : map.entrySet()) {
appendValueToMapList(reverseMap, entry.getValue(), entry.getKey());
}
return reverseMap;
}
/**
* Berücksichtigt, dass die Liste bereits Werte enthalten kann.
*
* @param map
* @param key
* @param value
* @param
* @param
* @return
*/
public static Map> appendValueToMapList(Map> map, K key, V value) {
if(map == null || key == null || value == null) return map;
List list = map.get(key);
if(list == null) {
List newList = new ArrayList<>();
newList.add(value);
map.put(key, newList);
}
else {
list.add(value);
}
return map;
}