This article explores different ways to find the maximum-value entry in a Kotlin Map.

1. Using maxBy() function

The recommended solution is to find the maximum value entry in the map is using the maxWith() function that accepts a Comparator to compare objects based on a field value.

Download Code

Output:

D=4

 
The above code can be further shortened using the maxBy() function, which returns the first entry yielding the largest value of the provided function or null if there are no entries.

Download Code

Output:

D=4

2. Using Collections.max() function

The Collections.max() function returns the maximum element of the specified collection, according to the order induced by the specified comparator. We can use it with Map.Entry.comparingByValue to find the maximum-value entry in the map, as shown below:

Download Code

Output:

D=4

3. Using Loop

We can also iterate over the map and keep track of the entry with the maximum value. This can be implemented as follows in Kotlin, using a loop.

Download Code

Output:

D=4

 
We can also iterate over the Map’s keys to find the key with the maximum value:

Download Code

Output:

D

 
If multiple keys have the maximum value, the above code returns the first key with the maximum value. To get all keys having the maximum value, we can do something like:

Download Code

Output:

[B, D]

That’s all about finding the maximum-value entry in a Kotlin Map.