This post will discuss how to find the key(s) having the maximum value in a Map in Java.

1. Using for-loop

The idea is to iterate through all the entries of the map and keep track of the entry with the maximum value so far. The following example demonstrates this using a for-loop. Note that if multiple keys have the same maximum value, the code returns the first key it finds with the maximum value.

Download  Run Code

Output:

D=4

 
You can also iterate over the map using the keySet() method and find the key with the maximum value:

Download  Run Code

Output:

D

2. Using Stream API

With Java 8 and later, you can use Stream API:

Download  Run Code

Output:

D=4

 
You can also get a stream of keys contained in the map and find the maximum-valued key:

Download  Run Code

Output:

D

 
Here’s another variation of the above approach using Map.Entry.comparingByValue:

Download  Run Code

Output:

D=4

3. Get all Mappings

To fetch all keys having the maximum value, first, find the maximum value in the map, then iterate over the map’s entries, and filter all entries with the maximum value. Here’s the complete code:

Download  Run Code

Output:

[B, D]

 
Here’s a version without using the Stream API:

Download  Run Code

Output:

[B, D]

That’s all about finding the key(s) having the maximum value in a Map in Java.