Java
Hashmap
Programming
Key-Value Pair
Data Structure

Java Hashmap How to get key from value?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Java HashMap is a fundamental data structure in Java, widely used for its capability to store data in key-value pairs. One common question among developers, especially those new to using HashMap, is how to retrieve a key from a given value. This operation is not as straightforward as finding a value based on a given key, primarily because HashMap is designed for fast retrieval of values from keys, not the other way around. The operation to find a key from a value doesn't directly exist as a method within the HashMap class, and the reasons pertain to the data structure's properties and design principles.

Understanding The Challenge

Java HashMap implements the Map interface and provides constant-time performance for the basic operations (get and put), assuming the hash function disperses elements properly among the buckets. Herein lies the primary focus: HashMap is optimized for key-to-value association, where each key is unique, and each key maps to exactly one value. Conversely, values can be duplicated across different keys. This characteristic complicates the reverse lookup (value-to-key) because multiple keys can potentially correspond to the same value.

Example of Key-Value Duplication

Suppose we have a HashMap populated as follows:

java
1HashMap<Integer, String> map = new HashMap<>();
2map.put(1, "Java");
3map.put(2, "Python");
4map.put(3, "Java");

The value "Java" is associated with both keys 1 and 3. Given "Java", it's ambiguous which key to return.

How to Retrieve Key from Value

Despite no native method to retrieve a key by value directly, it's straightforward to implement such functionality. We can iterate over the Map.Entry (key-value pairs) of the HashMap.

Example Implementation

java
1public List<Integer> getKeysFromValue(HashMap<Integer, String> map, String value) {
2    List<Integer> keys = new ArrayList<>();
3    for (Map.Entry<Integer, String> entry : map.entrySet()) {
4        if (entry.getValue().equals(value)) {
5            keys.add(entry.getKey());
6        }
7    }
8    return keys; // returns all keys matching the given value
9}

This method iterates over all entries in the HashMap, checks if the value of each entry matches the given value, and if so, adds the key to a list of keys, which is then returned.

Performance Considerations

It is important to note that the performance of this reverse lookup operation is linear in respect to the number of entries (O(n)), as it involves iterating through the entire HashMap. This is less efficient compared to the constant time complexity (O(1)) of standard get() or put() operations offered by HashMap.

FeatureDescriptionComplexity
Fast Key LookupRetrieve value for a specific keyO(1)
Reverse Lookup EfficiencyRetrieve keys for a specific valueO(n)
Allow Duplicate ValuesValues can be repeated across multiple keysApplicable
Key UniquenessEach key in the map is uniqueRequired

Other Considerations

If your use case frequently requires reverse lookups, consider these strategies:

  • BiMap: Using a bidirectional map, such as the BiMap from Google's Guava library, can provide efficient two-way lookup at the cost of enforcing unique values.
  • Maintain a Supplementary Map: Keep a separate HashMap that maps values back to keys. This is generally viable only if the values are unique.

Conclusion

Although retrieving a key from a value is not directly supported by Java HashMap due to its design and operation complexity characteristics, it is feasible with additional code that iterates over entries. Understanding when and how to efficiently retrieve a key based on a value, while taking into account the implications on performance and data integrity, is crucial for optimizing and justifying such operations in Java applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.