-Host OS: Windows10 Home ・ Guest OS: WSL2 Ubuntu 20.04 ・ Java8
To get the maximum value of HashMap whose 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 a 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);
a : 4
I was able to get the maximum value safely. If there are multiple maximum values and you want to get all of them, you can store them in a list.
The advantage of entrySet is that you can get both the key and the value in one loop.
Recommended Posts