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

前端 未结 2 1740
暗喜
暗喜 2021-02-02 07:15

I have a list, e.g like:

val list = listOf(\"orange\", \"apple\", \"apple\", \"banana\", \"water\", \"bread\", \"banana\")

How can i check how

2条回答
  •  春和景丽
    2021-02-02 07:57

    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}
    

提交回复
热议问题