Java
Map
Key-Value
Max Value
Programming

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.

Browse interview questions

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.

java
1import java.util.HashMap;
2import java.util.Map;
3
4public class MaxValueKeyExample {
5
6    public static void main(String[] args) {
7        // Create a map of product sales
8        Map<String, Integer> productSales = new HashMap<>();
9        productSales.put("Laptop", 150);
10        productSales.put("Smartphone", 200);
11        productSales.put("Tablet", 50);
12        productSales.put("Smartwatch", 75);
13        
14        // Find the product with the maximum sales
15        String maxSalesProduct = null;
16        int maxSales = Integer.MIN_VALUE;
17
18        for (Map.Entry<String, Integer> entry : productSales.entrySet()) {
19            if (entry.getValue() > maxSales) {
20                maxSales = entry.getValue();
21                maxSalesProduct = entry.getKey();
22            }
23        }
24
25        System.out.println("The product with the maximum sales is: " + maxSalesProduct);
26    }
27}

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:

  1. Initialize Variables: Start with a variable maxSales set to Integer.MIN_VALUE and maxSalesProduct set to null to store the maximum sales observed and the corresponding product name.
  2. Iterate Over Entries: Loop through each map entry.
  3. Find Maximum: Compare each value in the map to maxSales. If a value is greater, update maxSales and store the current key in maxSalesProduct.
  4. Output the Result: At the end of the loop, maxSalesProduct holds 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:

java
1import java.util.Comparator;
2import java.util.HashMap;
3import java.util.Map;
4import java.util.Optional;
5
6public class MaxValueKeyExampleUsingStreams {
7
8    public static void main(String[] args) {
9        Map<String, Integer> productSales = new HashMap<>();
10        productSales.put("Laptop", 150);
11        productSales.put("Smartphone", 200);
12        productSales.put("Tablet", 50);
13        productSales.put("Smartwatch", 75);
14
15        Optional<Map.Entry<String, Integer>> maxEntry = productSales.entrySet()
16                .stream()
17                .max(Map.Entry.comparingByValue());
18
19        maxEntry.ifPresent(entry ->
20                System.out.println("The product with the maximum sales is: " + entry.getKey()));
21    }
22}

Stream-based Solution Explanation

  1. Convert to Stream: entrySet().stream() initiates a stream of map entries.
  2. Find Maximum: Use the max() method with Map.Entry.comparingByValue() comparator to find the maximum value.
  3. Handle Optional: Since max() returns an Optional, use ifPresent() to safely manage the result without worrying about null values.

Summary Table

AspectDetails
Class/Interface UsedHashMap, Map, Map.Entry, Optional
Time ComplexityO(n)
Default Value for ComparisonInteger.MIN_VALUE
ApproachesTraditional Loop, Java 8 Stream API
Stream ComparatorMap.Entry.comparingByValue()
Empty Map ConsiderationsCheck if map is empty to prevent operations on null values
MutabilityEnsure 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.