Java HashMap – Complete Guide
■ Short Answer
■ No, not directly. A HashMap is designed for fast key → value lookups, not the other way around.
■■ Why?
Internally, a HashMap computes the hash of the key to find where to store or look up data. There is
no hashing mechanism for values. So when you do [Link]('apple'), Java can instantly find the
value because it hashes the key. But if you only know the value, there’s no direct index or
hash-based way to find which key(s) have that value.
■ How to do it (Indirectly)
If you need to find the key(s) for a given value, you must manually loop through all entries in the
map:
for ([Link] entry : [Link]()) { if ([Link]().equals(searchValue)) {
[Link]("Key: " + [Link]()); } }
■ Alternative: Use a BiMap (Two-way Map)
If you need frequent lookups both ways (key → value and value → key), you can use Guava’s
BiMap (from Google’s library). It allows inverse lookups directly, provided values are unique.
■ Summary
1 HashMap: Key → Value (O(1)), Value → Key (O(n))
2 BiMap: Key ↔ Value (O(1)) if values are unique
3 Custom solution: maintain two maps for bidirectional lookup
■ Tip
If your program often needs to look up both ways, maintain two maps simultaneously for efficient
lookup in both directions.
■ That’s how HashMap works — and how you can extend it for two-way lookups efficiently.