+ 2

Swapping Keys and values into my second HashMap.

example...in python...... but looking to do similar in java. dict1 = dict(zip(list1, list2) dict2 = dict(zip(list2, list1) # see how the lists are swapped in this dict. How can I swap the keys and values of my first HashMap into my second HashMap? I've had a look in the java docs on-line, but the constructor and "putAll" only takes a whole HashMap. (as I understand).

28th Nov 2019, 11:07 PM
rodwynnejones
rodwynnejones - avatar
5 Respuestas
+ 3
rodwynnejones you were on the right track there with keySet() . Here is an example. https://code.sololearn.com/cb4GFoQCZkdt/?ref=app
29th Nov 2019, 6:46 AM
Tibor Santa
Tibor Santa - avatar
+ 2
@Avinesh Thank you for responding....that's what I ended up doing. ...but now I'm thinking about it.......maybe I can do a for-each loop using the myHashMap.keySet() and do it that way........but that's for tomorrow. Thanks anyway.
29th Nov 2019, 12:11 AM
rodwynnejones
rodwynnejones - avatar
+ 2
This is what I ended up with.....might be of interest to another beginner:- HashMap<Character, Integer> HashMapOne = new HashMap<Character, Integer>(); HashMap<Integer, Character> HashMapTwo = new HashMap<Integer, Character>(); HashMapOne.put('a', 1); HashMapOne.put('b', 2); HashMapOne.put('c', 3); // etc.... for(Character x: HashMapOne.keySet()) HashMapTwo.put(HashMapOne.get(x), x);
30th Nov 2019, 12:45 AM
rodwynnejones
rodwynnejones - avatar
+ 1
I doubt if you can do that using a single line function in java. It has to be completely manually entered.
28th Nov 2019, 11:49 PM
Avinesh
Avinesh - avatar
+ 1
Only thing to be noted, is that hashmap has unique keys but not necessary unique values. So if you swap the keys/values when some keys point to the same value, you might lose some data. Of course not the case with this particular example.
30th Nov 2019, 6:10 AM
Tibor Santa
Tibor Santa - avatar