Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

swap keys and duplicate values in hashmap

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

}
}
 
Ranch Hand
Posts: 954
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.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic