【问题标题】:How to replace duplicate elements in Hash Map如何替换哈希图中的重复元素
【发布时间】:2019-02-14 06:04:44
【问题描述】:

我正在尝试用新的唯一 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);
  }

【问题讨论】:

  • 元素顺序 - 使用LinkedHashMap 来保留顺序而不是HashMap
  • 好的。那么如何替换重复的值呢?
  • 如果有 2 组或更多组 重复项怎么办?
  • 它们必须替换为 uuids

标签: java arraylist hashmap maps


【解决方案1】:

你很亲密:

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}

【讨论】:

    【解决方案2】:

    首先,将你的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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      相关资源
      最近更新 更多