2

I need to have a map between 2 kind of objects, lets say, for demonstrarion purposes, String and Long.

I know a HashMap has an O(1) search performance, which is great. I am using something like this:

HashMap<String, Long> a = new HashMap<String, Long>();

This works great when I want to search by the key. However, now I do need to also find the key searching by value.

If I start iterating over keys, then I will lose the performance.

The first option I have thought about is to create another HashMap the other way around.

HashMap<Long, String> reverseA = new HashMap<Long, String>();

And whenever I write in one, write in the other one.

Isn't there an specific class to be able to search by keys and by values, with that great performance?

Should I create my own class with both HashMaps?

Any other solution?

5
  • Perhaps Guava's BiMap contains what you're looking for. Commented Sep 29, 2017 at 6:50
  • But of course they key is unique and the value is maybe not so Commented Sep 29, 2017 at 6:51
  • @ScaryWombat: Well, if the reverseA map is an option, then the values better be unique or there will be a bit of inconsistency. Commented Sep 29, 2017 at 6:55
  • If you don't want to use third API, why not filter the map using new Streaming API which does not have overhead, unless you do a terminal call? Commented Sep 29, 2017 at 7:00
  • Why not use 2 HashMaps? It would be better than adding a new dependency to Guava just for this one case. Commented Sep 29, 2017 at 7:08

2 Answers 2

6

You can use Guava BiMap :

BiMap<String, Long> map = HashBiMap.create();
map.put("a", 1L);
map.put("b", 2L);
map.put("c", 3L);

System.out.println(map.get("b")); // 2L
System.out.println(map.inverse().get(2L)); // "b"

An other alternative is Apache commons BidiMap :

BidiMap<String, Long> map = new DualHashBidiMap<>();
map.put("a", 1L);
map.put("b", 2L);
map.put("c", 3L);

System.out.println(map.get("b")); // 2L
System.out.println(map.inverseBidiMap().get(2L)); // "b"
Sign up to request clarification or add additional context in comments.

Comments

0

Java itself doesn't offer anything, but Guava has BiMap, which has an inverse view that supports efficient reverse lookups.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.