To find the element with the minimum number of occurrences in a list in Kotlin, you can use a map to count the occurrences.
In this example,
data
with several integer elements.fun main() {
val data = listOf(1, 2, 2, 3, 3, 3, 4)
val count = mutableMapOf<Int, Int>()
for (num in data) {
count[num] = count.getOrDefault(num, 0) + 1
}
var leastCommon = data[0]
var minCount = Int.MAX_VALUE
for ((key, value) in count) {
if (value < minCount) {
minCount = value
leastCommon = key
}
}
println("Element with the minimum occurrences is: $leastCommon")
}
Element with the minimum occurrences is: 1
In this example,
words
with several string elements.fun main() {
val words = listOf("apple", "banana", "apple", "orange", "banana", "apple")
val count = mutableMapOf<String, Int>()
for (word in words) {
count[word] = count.getOrDefault(word, 0) + 1
}
var leastCommon = words[0]
var minCount = Int.MAX_VALUE
for ((key, value) in count) {
if (value < minCount) {
minCount = value
leastCommon = key
}
}
println("Element with the minimum occurrences is: $leastCommon")
}
Element with the minimum occurrences is: orange
In this tutorial, we learned How to find the Element with Minimum Number of Occurrences in a List in Kotlin language with well detailed examples.