K.Os
K.Os

Reputation: 5506

Kotlin - how to find number of repeated values in a list?

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?

Upvotes: 75

Views: 59685

Answers (2)

sol4me
sol4me

Reputation: 15708

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}

Upvotes: 200

Related Questions