Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap keys and values in a Map elegantly

Tags:

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 :)

like image 255
kostja Avatar asked Dec 14 '10 07:12

kostja


1 Answers

Map<String, Integer> map = new HashMap<>();
Map<Integer, String> swapped = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
like image 171
Nikita Marshalkin Avatar answered Oct 04 '22 00:10

Nikita Marshalkin