To find the element with the maximum number of occurrences in a list in Kotlin, you can use the groupingBy
and maxBy
functions.
In this example,
list
containing elements.groupingBy
function with eachCount
to count the occurrences of each element in the list.maxBy
function to find the element with the maximum count.fun main() {
val list = listOf("a", "b", "c", "a", "b", "a")
val maxElement = list.groupingBy { it }.eachCount().maxBy { it.value }?.key
println("Element with maximum occurrences: $maxElement")
}
Element with maximum occurrences: a
In this example,
numbers
containing integers.groupingBy
function with eachCount
to count the occurrences of each integer in the list.maxBy
function to find the integer with the maximum count.fun main() {
val numbers = listOf(1, 2, 3, 2, 1, 1, 3, 1)
val maxNumber = numbers.groupingBy { it }.eachCount().maxBy { it.value }?.key
println("Number with maximum occurrences: $maxNumber")
}
Number with maximum occurrences: 1
In this tutorial, we learned How to find the Element with Maximum Number of Occurrences in a List in Kotlin language with well detailed examples.