我正在尝试用新的唯一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);
}
答案 0 :(得分:4)
您很亲密:
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}
答案 1 :(得分:1)
首先,将hm
映射中的键和值反转为Multimap
,然后将值重写为自己的map.code,如下所示:
Multimap<String,Integer> reverseMap = ArrayListMultimap.create();
hm.entrySet().stream()
.forEach(integerStringEntry -> reverseMap.put(integerStringEntry.getValue(),integerStringEntry.getKey()));
reverseMap.keySet().forEach(s -> reverseMap.get(s).stream()
.skip(1L)
.forEach(integer -> {
String uuids = UUID.randomUUID().toString().replace("-", "");
hm.put(integer,uuids);
}));
System.out.println(hm);
输出为:
{100=1111111111, 101=5252, 102=2e3586d248e3413687ff55dc17817c7d, 103=4589857}