[Java] [Java] How to get the maximum value of HashMap

1 minute read

Development environment/version

・Host OS: Windows10 Home ・Guest OS: WSL2 Ubuntu20.04 ・Java8

Purpose

Get the maximum value of HashMap in which key type is String and value type is Integer.

Implement using the EntrySet method. Below is the actual code


public static void main(String[] args) {
  String arr[] = {"a", "a", "a", "a", "b", "b", "b", "c", "c", "d"};
  Map<String, Integer> map = new HashMap<>();

// Store array elements in map
  for (String string :arr) {
    if (map.get(string) == null) {
      map.put(string, 1);
    } else {
      map.put(string, map.get(string) + 1);
    }
  }

// Initialize the maximum value and the key at that time
  String maxKey = null;
  Integer maxValue = 0;

//Get the map key and value one by one with the entrySet method
for (Map.Entry<String, Integer> entry: map.entrySet()) {

//Compare the maximum value and Value, and if Value is large, substitute the key and Value at that time
  if (entry.getValue()> maxValue) {
    maxKey = entry.getKey();
    maxValue = entry.getValue();
  }
}
System.out.println(maxKey + ": "+ maxValue);

result

a: 4

I was able to successfully obtain the maximum value. If there are multiple maximum values and you want to retrieve all of them, you should store them in a list.

The advantage of entrySet is that you can get both key and value in one loop.

Tags:

Updated: