javacollectionshashmap

How to swap keys and values in a Map elegantly


I already know how to do it the hard way and got it working - iterating over entries and swapping "manually". But i wonder if, like so many tasks, this one can be solved in a more elegant way.

I have read this post, unfortunately it does not feature elegant solutions. I also have no possibility to use any fancy Guava BiMaps or anything outside the jdk (project stack is already defined).

I can assume that my map is bijective, btw :)


Solution

  • The standard API / Java runtime doesn't offer a bi-directional map, so the only solution is to iterate over all entries and swap them manually.

    What you can do is create a wrapper class which contains two maps and which does a dual put() internally so you have fast two views on the data.

    [EDIT] Also, thanks to open source, you don't have to include a third party library, you can simply copy the classes you need into your own project.