Find Maximum Value Iteratively
Iterate over all the values of the map to find the maximum value. For this, create a null Entry
of Map
type and then iterate over all the values of the map. Whenever you get a bigger value or null value we assign it to Entry and at the end simply print the value of Entry.
import java.util.*;
public class MaxValueInMap {
public static void main(String args[]) {
Map<String, Integer> coursePrices = new HashMap<>();
Map.Entry<String, Integer> maxPrice = null;
coursePrices.put("Java", 5000);
coursePrices.put("Python", 3000);
coursePrices.put("CPP", 4000);
coursePrices.put("Android", 8000);
for (Map.Entry<String, Integer> price : coursePrices.entrySet()) {
if (maxPrice == null || price.getValue().compareTo(maxPrice.getValue()) > 0) {
maxPrice = price;
}
}
System.out.println("Maximum price is: " + maxPrice.getValue());
}
}
Save the file and run the program using the following command:
javac MaxValueInMap.java && java MaxValueInMap