What if I need to quickly search not only by the key but also by value. In other words, is there a construction like key-key as opposed to key-value?
Asked
Active
Viewed 192 times
8
-
1Do notice that Guava's `BiMap` are basically two `Map`s put together and kept symmetric, so you could just do that yourself if you don't want to add an extra library. – Viruzzo Jan 16 '12 at 15:44
3 Answers
9
Sounds like you want a bimap - I'd use the implementations in Guava if I were you; there's a BiMap
interface, and various implementations such as HashBiMap
and ImmutableBiMap
.
Note that you generally view a BiMap
from one "side" (K1 to K2), and just call inverse()
to get the opposite view of things (K2 to K1).

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
5
Several libraries have something like that. For example, Google Guava has a BiMap
(bidirectional map). Unfortunately there's no bidirectional map in the standard Java library.

Jesper
- 202,709
- 46
- 318
- 350
0
To clarify, you would have some sort of map with the following key:value pairs:
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "Freddy");
map.put("bar", "Bobby");
Then, you would want to do map.get("foo") and get Freddy, or do map.get("Freddy") and get foo?
If so, check this post out.