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?
The elements in the resulting list are in the same order as they were in the source array. Returns a list containing only elements from the given array having distinct keys returned by the given selector function. The elements in the resulting list are in the same order as they were in the source array.
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With