如何删除映射中重复的键值对

nit*_*ger 2 java dictionary key-value

仅当每个键在map1中具有唯一值时,我才陷入如何将键值对从map1传输到map2的问题。

假设我有以下地图:

  • 地图1: [1,2] [2,4] [4,4]
  • 地图2:[1,2] [2,4]

我想算法是:

  1. 循环遍历第一个映射中的条目。
  2. 向map2添加一个键。
  3. 将一个值添加到一个集合中,以检查 map2 的值
  4. 如果值重复,则该值不会添加到集合中,并且会忽略将其相应的键添加到 map2 中。

代码片段:

public static <K,V> Map<K,V> unique (Map<K,V> m) {
  Map<K,V> newMap = new ArrayMap<K,V>();

  //Remember all values in the newMap.
  Set<V> holding = new ArraySet<V>(newMap.values());

  for (Map.Entry<K, V> graphEntry : m.entries()) {
     //not sure.
  }

  return newMap;  
}
Run Code Online (Sandbox Code Playgroud)

我的想法应该如何在正确的轨道上完成?在这里完全迷失了。

Lui*_*oza 5

当且仅当键不在地图中时,从Map<K, V>创建一个将添加项目的项目。Map<V, K>使用它Map<V, K>,重新创建您的Map<K, V>.

public static <K, V> Map<K, V> createMap(Map<K, V> m) {
    Map<K, V> map = new HashMap<K, V>();
    Map<V, K> tmpMap = new HashMap<V, K>();
    for(Map.Entry<K, V> entry : m.entrySet()) {
        if (!tmpMap.containsKey(entry.getValue())) {
            tmpMap.put(entry.getValue(), entry.getKey());
        }
    }
    for(Map.Entry<V, K> entry : tmpMap.entrySet()) {
        map.put(entry.getValue(), entry.getKey());
    }
    return map;
}
Run Code Online (Sandbox Code Playgroud)

如果需要保留数据的保存顺序,请使用LinkedHashMap代替HashMap