这个怎么样?
public HashMap getDuplicateValues(HashMap in)
{
// Clone input HashMap because we're removing stuff from it
in = (HashMap)in.clone();
HashMap rval = new HashMap();
Object[] keys = in.keySet().toArray();
// iterate through all keys
for(int x=0;x<keys.length;x++) {
Object value = in.get(keys[x]);
in.remove(keys[x]);
// if value is in input HashMap, store it in duplicate HashMap because it has another value
if(in.containsValue(value)) {
rval.put(keys[x],value);
}
// if value is in duplicate HashMap, store it also because it HAD another value earlier
if(rval.containsValue(value)) {
rval.put(keys[x],value);
}
}
return(rval);
}
此方法将返回输入 HashMap 中所有重复值的键/值对。
测试代码:
HashMap map = new HashMap();
map.put("1","2");
map.put("2","1");
map.put("3","8");
map.put("4","4");
map.put("5","6");
map.put("6","8");
map.put("7","3");
map.put("8","4");
map.put("9","4");
HashMap dups = getDuplicateValues(map);
System.out.println("MAP = "+map);
System.out.println("DUP = "+dups);
输出:
MAP = {3=8, 2=1, 1=2, 7=3, 6=8, 5=6, 4=4, 9=4, 8=4}
DUP = {3=8, 6=8, 4=4, 9=4, 8=4}