Kotlin - how to find number of repeated values in a list?
34,178
Solution 1
list.count { it == "apple" }
Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/, https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/count.html
Solution 2
One way to find all the repeated values in a list is using groupingBy and then filter the values which are > 1
. E.g.
val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana")
println(list.groupingBy { it }.eachCount().filter { it.value > 1 })
Output
{apple=2, banana=2}
Related videos on Youtube
Author by
K.Os
Updated on July 09, 2022Comments
-
K.Os almost 2 years
I have a list, e.g like:
val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana")
How can i check how many times apple is duplicated in this list?
-
Simon Cedergren Malmqvist about 4 yearsIf you don't care of knowing which index has an overlapping value (e.g. for validation),
println(list.groupingBy { it }.eachCount().any { it.value > 1 })
would be more efficient since it stops on the first occurrence. -
Caio about 2 yearsI added this extension function on my projects for find repeated items in Iterable by a Predicate: inline fun <T, K> Iterable<T>.findRepeatedItemsBy(crossinline keySelector: (T) -> K):Map<K, Int> = groupingBy(keySelector) .eachCount() .filter { it.value > 1 }