gpt4 book ai didi

java - 如何替换 HashMap 中的重复元素

转载 作者:行者123 更新时间:2023-12-01 16:44:36 27 4
gpt4 key购买 nike

我正在尝试用新的唯一 ID 替换 HashMap 中的重复值。这样元素的顺序不会丢失,但重复的值会被更改为新的值。

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 - 如何替换 HashMap 中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684140/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com