Kotlin Map minWith()
Syntax & Examples
Syntax of Map.minWith()
There are 2 variations for the syntax of Map.minWith() extension function. They are:
1.
fun <K, V> Map<out K, V>.minWith( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>
This extension function returns the first entry having the smallest value according to the provided comparator.
2.
fun <K, V> Map<out K, V>.minWith( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>?
This extension function
✐ Examples
1 Get entry with minimum character value in the map
In this example,
- We create a map named
map1
containing integer keys and character values. - We then apply the
minWith()
function onmap1
, using a custom comparator to compare values. - As a result, the entry with the minimum character value in
map1
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map1.minWith(Comparator { entry1, entry2 -> entry1.value.compareTo(entry2.value) })
println(result)
}
Output
1=a
2 Get entry with minimum integer value in the map
In this example,
- We create a map named
map2
containing character keys and integer values. - We then apply the
minWith()
function onmap2
, using a custom comparator to compare values. - As a result, the entry with the minimum integer value in
map2
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map2.minWith(Comparator { entry1, entry2 -> entry1.value.compareTo(entry2.value) })
println(result)
}
Output
a=1
Summary
In this Kotlin tutorial, we learned about minWith() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.