• Post Reply Bookmark Topic Watch Topic
  • New Topic

swap keys and duplicate values in hashmap  RSS feed

 
Vishal Bhadur Verma
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

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

Any suggestion on this ?
 
Vishal Bhadur Verma
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found the solution for this and this is working fine :

public class ReversingHashMap {

/**
* @param args
*/
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
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());
}

}
}
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So what is your question and please use code tags so code can be understood easily.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!