nit*_*ger 2 java dictionary key-value
仅当每个键在map1中具有唯一值时,我才陷入如何将键值对从map1传输到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)
我的想法应该如何在正确的轨道上完成?在这里完全迷失了。
当且仅当键不在地图中时,从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。
| 归档时间: |
|
| 查看次数: |
19858 次 |
| 最近记录: |