Home > DeveloperSection > Forums > swap keys and duplicate values in hashmap
Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    April-22-2015 1:07 AM

 Java Java 
Ratings:


 1 Reply(s)
 521  View(s)
Rate this:
Hey Everyone,
I have interesting question on hash map and it says : 

I have a hash map with values : {"1-a","2-a","3-b","4-b"} 
Keys Values 
1 a 
2 a 
3 b 
4 b 

I need to swap the key values with losing the data , means the new hash map should be : 
Keys Values 
a 1,2 
b 3,4 

Can anyone suggest me the way to do this?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    April-22-2015 7:34 AM

Finally after a lot of research i have done it 
Map<String, Set<String> > newmap = new HashMap<String, Set<String> >(); 
map.put("1", "a"); 
map.put("2", "a"); 
map.put("3", "b"); 
map.put("4", "b"); 
System.out.println("before Reversing"); 
for (Map.Entry<String, String> entry : map.entrySet()) 

System.out.println("The key ::"+entry.getKey()+":: The value"+entry.getValue()); 

for (Map.Entry<String, String> entry : map.entrySet()) 

String oldVal = entry.getValue(); 
String oldKey = entry.getKey(); 
Set<String> newVal = null; 
if (newmap.containsKey(oldVal)) 

newVal = newmap.get(oldVal); 
newVal.add(oldKey); 

else 

newVal= new HashSet<>(); 
newVal.add(oldKey); 

newmap.put(oldVal, newVal); 

System.out.println("After Reversing"); 
for (Map.Entry<String, Set<String>> entry : newmap.entrySet()) 

System.out.print("The key ::"+entry.getKey()+":: The value"+entry.getValue()); 


}

Don't want to miss updates? Please click the below button!

Follow MindStick