Find Smallest and Largest Value in a Map

This Java tutorial will discuss different techniques to find the smallest and largest value in HashMap. We will discuss techniques from simple iterations, Collections and Stream APIs. We will be using the following Map for examples. 

Map<String, Integer> map = Map.of("key1", 100, "key2", 200, "key3", 300);

1. Using Java Streams 

Java streams provide a lot of useful classes and factory methods for performing various reduction operations. Here we have used Stream.max() which returns the maximum element of the stream based on the Comparator that compares Map.Entry in natural order on value. Similarly, we can use Stream.min() which returns the minimum value in the map. 

Optional<Entry<String, Integer>> maxEntry = map.entrySet().stream().max(Map.Entry.comparingByValue());
Integer maxValue = maxEntry.get().getValue();  

Optional<Entry<String, Integer>> minEntry = map.entrySet().stream().min(Map.Entry.comparingByValue());
Integer minValue = minEntry.get().getValue();   

2. Using Collections

This is one of the straightforward and easy ways to find the smallest & largest value from a Map. The Collections class provides max() and min() methods that use the specified Comparator to find the smallest or the largest entry from the Map

In the given example, all the elements in the collection are mutually Comparable and thus return the max/min element. 

Entry<String, Integer> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Entry::getValue));
Integer maxValue = maxEntry.getValue();  

Entry<String, Integer> minEntry = Collections.min(map.entrySet(), Comparator.comparing(Entry::getValue));
Integer minValue = minEntry.getValue(); 

3. Using Iteration

In this approach, we need to iterate over the elements of the provided map to pick the lowest/highest element and store them in a variable. Note that this approach is inefficient when the number of occurrences of the element is high.

Entry<String, Integer> maxEntry = null;
Entry<String, Integer> minEntry = null;

for (Map.Entry<String, Integer> currentEntry : map.entrySet()) {
  if (maxEntry == null || currentEntry.getValue() > maxEntry.getValue()) {
    maxEntry = currentEntry;
  } else {
    minEntry = currentEntry;
  }
}

Integer maxValue = maxEntry.getValue(); 
Integer minValue = minEntry.getValue(); 

4. Conclusion

In this short Java tutorial, we learned the different ways to find the minimum and the maximum value in a map using different techniques from iteration to Stream APIs. The efficient way to find the smallest and largest value is by using Stream API or by using collections instead of iterating the elements one by one. 

Happy Learning !!

Sourcecode on Github

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.