我想在地图中切换键和值,以便:Map<K, V> becomes Map<V, Set<K>>.
所以:
1 = a
2 = b
3 = a
将成为:
a=[1, 3],
b=[2]
我尝试了以下操作:
public static <K, V> Map<V, Set<K>> inverse(Map<K, V> map) {
Map<V, Set<K>> m = new HashMap<V, Set<K>>();
HashSet<K> set = new HashSet<K>();
for (Map.Entry<K, V> e : map.entrySet()) {
if (set.size() < 1) {
set.add(e.getKey());
m.put(e.getValue(), set);
}
if (m.containsKey(e.getValue())) {
m.remove(set);
set.add(e.getKey());
m.put(e.getValue(), set);
}
}
return m;
}
但是这只会返回a = [1,3]
m
中删除任何内容,当您使用现有键在地图中放置内容时,值将更新:map.put(key, value);
map.put(key, newValue);
输出:键:键值:newValue