Reputation: 123
I'm trying to replace duplicate values in Hash Map with new unique ids. so that order of elements is not lost but duplicate values alone get changed to new ones.
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);
}
Upvotes: 0
Views: 150
Reputation: 1430
First,reverse the key and value in your hm
map into a Multimap
,then rewrite value to your own map.code like this:
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);
The output is:
{100=1111111111, 101=5252, 102=2e3586d248e3413687ff55dc17817c7d, 103=4589857}
Upvotes: 1
Reputation: 7917
You were close:
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);
Output:
{100=1111111111, 101=5252, 102=ba297d9412654591826d4e496f643b4c, 103=4589857}
Upvotes: 4