0

I have a hash map and values in it. Now i want to set the values in the map as keys and keys as values. Can anyone suggest any idea?

My Map is

Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");

Now i want to create an another map and put it in other way as i told above. ie,

Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");

Anybody has idea? Thanks

H.-Dirk Schmitt
  • 1,159
  • 8
  • 14

3 Answers3

2

Like so:

Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
    col2.put(e.getValue(), e.getKey());
}
Boann
  • 48,794
  • 16
  • 117
  • 146
0

Assuming your values are unique in your hashmap, you can do like this.

// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
     String currentValue = valueIterator.next();
     // Find the value in old HashMap
     Iterator<String> keyIterator = col.keySet().iterator();
     while(keyIterator.hasNext()){
          String currentKey = keyIterator.next();
          if (col.get(currentKey).equals(currentValue)){
               // When found, put the value and key combination in new HashMap
               col1.put(currentValue, currentKey);
               break;
          }
     }
}
Ravindra Gullapalli
  • 9,049
  • 3
  • 48
  • 70
0

Create another Map and iterate through keys/values one by one and put in new Map. finally delete old one.

SztupY
  • 10,291
  • 8
  • 64
  • 87
vikbehal
  • 1,486
  • 3
  • 21
  • 48