Reputation: 907
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?
Upvotes: 8
Views: 200
Reputation: 535
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.
Upvotes: 0
Reputation: 206766
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.
Upvotes: 5
Reputation: 1499760
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).
Upvotes: 9