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

前端 未结 2 1732
暗喜
暗喜 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}
    
    0 讨论(0)
  • 2021-02-02 08:01
    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

    0 讨论(0)
提交回复
热议问题