There are 2 variations for the syntax of Map.minWith() extension function. They are:
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.
fun <K, V> Map<out K, V>.minWith( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>?
This extension function
In this example,
map1
containing integer keys and character values.minWith()
function on map1
, using a custom comparator to compare values.map1
is returned.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)
}
1=a
In this example,
map2
containing character keys and integer values.minWith()
function on map2
, using a custom comparator to compare values.map2
is returned.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)
}
a=1
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.