Finding Key associated with max Value in a Java Map
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
To effectively manipulate data in Java, understanding how to work with collections like maps can significantly enhance your code's functionality. A common task when dealing with maps is finding the key associated with the maximum value. This article provides an in-depth exploration of how to achieve this, covering technical explanations, illustrative examples, and additional subtopics to offer a thorough comprehension of the process.
Working with Java Maps
A Map in Java is an object that maps keys to values, where each key is unique and is associated with exactly one value. The primary implementations of the Map interface are HashMap, TreeMap, and LinkedHashMap. Here, we will focus on using a HashMap for our examples, albeit the logic can be extended to other Map implementations.
Example Scenario
Consider a Map<String, Integer> where the keys represent product names and the values represent their respective sales numbers. Our goal is to identify the product with the highest sales numbers — the key with the maximum value.
Technical Explanation
In the given example, we traverse the map using an enhanced for-loop iterating over the entry set of the map. The entrySet() method returns a set of key-value pairs contained in the map. Specifically, we perform the following steps:
- Initialize Variables: Start with a variable
maxSalesset toInteger.MIN_VALUEandmaxSalesProductset tonullto store the maximum sales observed and the corresponding product name. - Iterate Over Entries: Loop through each map entry.
- Find Maximum: Compare each value in the map to
maxSales. If a value is greater, updatemaxSalesand store the current key inmaxSalesProduct. - Output the Result: At the end of the loop,
maxSalesProductholds the key with the maximum value.
Considerations
- The algorithm has a time complexity of O(n), where n is the number of key-value pairs in the map, as it involves a single traversal.
- Ensure the map is not empty before performing the iteration to prevent handling unnecessary logic when no data exists.
Using Java 8 Streams
Java 8 introduced the Streams API, providing a more declarative approach to operations on collections, including maps. Below is an alternative approach using streams:
Stream-based Solution Explanation
- Convert to Stream:
entrySet().stream()initiates a stream of map entries. - Find Maximum: Use the
max()method withMap.Entry.comparingByValue()comparator to find the maximum value. - Handle Optional: Since
max()returns anOptional, useifPresent()to safely manage the result without worrying aboutnullvalues.
Summary Table
| Aspect | Details |
| Class/Interface Used | HashMap, Map, Map.Entry, Optional |
| Time Complexity | O(n) |
| Default Value for Comparison | Integer.MIN_VALUE |
| Approaches | Traditional Loop, Java 8 Stream API |
| Stream Comparator | Map.Entry.comparingByValue() |
| Empty Map Considerations | Check if map is empty to prevent operations on null values |
| Mutability | Ensure the map is not being modified during iteration to avoid ConcurrentModificationException |
Further Enhancements
- Handling Ties: If multiple keys have the maximum value, additional logic is required to handle ties. For instance, store keys in a list in case of a tie.
- Parallel Streams: For very large datasets, consider using parallel streams to enhance performance, keeping in mind the thread-safety of the map.
- Custom Comparators: Implement custom comparators for complex data type values, offering flexibility in comparison criteria.
By understanding and utilizing these techniques, you can effectively manage and manipulate map data structures in Java, tailoring solutions to a wide array of practical scenarios.
Related reading
- Finding Number of Cores in Java
- Finding the first duplicate in an int array, java
- Finding the max/min value in an array of primitives using Java
- Finding the max/min value in an array of primitives using Java
- Finding the second highest number in array in Java
- findResource returning null when module-info.java is present, why is that?
- FixedThreadPool vs CachedThreadPool the lesser of two evils
- Flaky tests of async spring controller with MockMvc

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.