Finding Maximum Value Using Iteration
One way to find the maximum value in a Map is by iterating through all entries and keeping track of the maximum value found so far. This approach works with any Map implementation.
What is Map.Entry?
Map.Entry
is an interface that represents a key-value pair in a Map. It provides methods to access both the key and the value in the pair.
Implementing the Iterative Approach
Let's modify our Java program to find the maximum course price using iteration:
-
Open the MaxValueInMap.java
file in the WebIDE
-
Replace the existing code with the following:
import java.util.*;
public class MaxValueInMap {
public static void main(String args[]) {
// Create a HashMap to store course prices
Map<String, Integer> coursePrices = new HashMap<>();
// Variable to store the entry with maximum price
Map.Entry<String, Integer> maxEntry = null;
// Add key-value pairs to the map
coursePrices.put("Java", 5000);
coursePrices.put("Python", 3000);
coursePrices.put("CPP", 4000);
coursePrices.put("Android", 8000);
System.out.println("Course price map: " + coursePrices);
// Iterate through each entry in the map
for (Map.Entry<String, Integer> entry : coursePrices.entrySet()) {
// If maxEntry is null OR current entry's value is greater than maxEntry's value
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
// Print the maximum price and its corresponding course
System.out.println("Course with maximum price: " + maxEntry.getKey());
System.out.println("Maximum price: " + maxEntry.getValue());
}
}
-
Save the file
-
Run the program with:
javac MaxValueInMap.java && java MaxValueInMap
You should see output similar to:
Course price map: {Java=5000, CPP=4000, Android=8000, Python=3000}
Course with maximum price: Android
Maximum price: 8000
How the Iteration Works
- We create a
maxEntry
variable initially set to null
- We iterate through each entry in the map using the
entrySet()
method
- For each entry, we compare its value with the current maximum value
- If the current entry has a greater value, or if
maxEntry
is still null
, we update maxEntry
- After completing the iteration,
maxEntry
holds the entry with the maximum value
This approach is useful when you need both the key and the value of the maximum entry.