我正在尝试用新的唯一ID替换Hash Map中的重复值。这样就不会丢失元素的顺序,而是仅将重复值更改为新值。
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"1111111111");
hm.put(101,"5252");
hm.put(102,"1111111111");
hm.put(103,"1111111111");
for(int i=0;i<hm.size;hm++){
String uuids = UUID.randomUUID().toString().replace("-", "");
hm.put(i, uuids);
}
最佳答案
您接近:
Map<Integer, String> hm = new LinkedHashMap<>();
hm.put(100, "1111111111");
hm.put(101, "5252");
hm.put(102, "1111111111");
hm.put(103, "4589857");
Set<String> seen = new HashSet<>();
for (Map.Entry<Integer, String> e : hm.entrySet()) {
if (!seen.add(e.getValue())) { //if (the 'seen' set already has that value)
hm.replace(e.getKey(), UUID.randomUUID().toString().replace("-", ""));
}
}
System.out.println(hm);
输出:
{100=1111111111, 101=5252, 102=ba297d9412654591826d4e496f643b4c, 103=4589857}
关于java - 如何替换哈希图中的重复元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54684140/