SWAP KEYS AND DUPLICATE VALUES IN HASHMAP

Mayank Tripathi

Total Post:397

Points:3117
Posted by  Mayank Tripathi
Java 
 784  View(s)
Ratings:
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?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: swap keys and duplicate values in hashmap

    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()); 


    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!