如何替换哈希映射中的重复元素

问题描述 投票:0回答:2

我正在尝试用新的唯一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);
  }
java arraylist hashmap maps
2个回答
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
投票

首先,将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}
© www.soinside.com 2019 - 2024. All rights reserved.