2

Its a starter question, I want to swap keys with values and vice versa of a HashMap. Here's what I've tried so far.

import java.util.HashMap;
import java.util.Map;

class Swap{
    public static void main(String args[]){

        HashMap<Integer, String> s = new HashMap<Integer, String>();

        s.put(4, "Value1");
        s.put(5, "Value2");

        for(Map.Entry en:s.entrySet()){
            System.out.println(en.getKey() + " " + en.getValue());
        }
    }
}
Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50

2 Answers2

8

You'll need a new Map, since the keys and values in your example have different types.

In Java 8 this can be done quite easily by creating a Stream of the entries of the original Map and using a toMap Collector to generate the new Map :

Map<String,Integer> newMap = 
    s.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getValue,Map.Entry::getKey));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • That was very simple and elegant but i'm using a earlier version. – Hitesh Misro Jul 26 '16 at 12:55
  • 1
    @HiteshkumarMisro Well, in earlier Java versions you'll have to create a new `Map`, iterate over the entrySet() of the original Map using a loop, and call `newMap.put(entry.getValue(),entry.getKey())` for each entry. – Eran Jul 26 '16 at 12:58
2

As suggested by Eran, I write a simple demo to swap key and value of a hashmap with another hashmap.

import java.util.HashMap;
import java.util.Map;

class Swap {
    public static void main(String args[]) {

        HashMap<Integer, String> s = new HashMap<Integer, String>();

        s.put(4, "Value1");
        s.put(5, "Value2");

        for (Map.Entry en : s.entrySet()) {
            System.out.println(en.getKey() + " " + en.getValue());
        }

        /*
         * swap goes here
         */
        HashMap<String, Integer> newMap = new HashMap<String, Integer>();
        for(Map.Entry<Integer, String> entry: s.entrySet()){
            newMap.put(entry.getValue(), entry.getKey());
        }

        for(Map.Entry<String, Integer> entry: newMap.entrySet()){
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}
Eugene
  • 10,627
  • 5
  • 49
  • 67