How to create a 2 way map in java

Viewed 38996

I need a data structure to store string-int value pairs in an 1:1 relationship, and being able too look up from either way their counterpart.

I wrote a class with a Hashtable and a String array and stored the data 2 times and used the built in functions for lookup.

My question is that is there a nicer way to accomplish this? And by nicer I mean being efficient and not storing the data 2 times, and preferably without writing a ton of code either :P.

7 Answers

definitely w/o writing a ton of code → in lambda
from Your Map<String,Integer> map You get the inverted map by

Map<Integer,String> inverted = map.keySet().stream().collect(Collectors.toMap( s -> map.get( s ), s -> s ) );
Related