Kotlin – 如何查找列表中的重复值的数量?

我有一个列表,例如:

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

我该如何检查苹果在这个列表中被复制了多少次?

 list.count { it == "apple" } 

文档: https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/,https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/count.html

一种找到列表中所有重复值的方法是使用groupingBy ,然后过滤> 1的值。 例如

val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana") println(list.groupingBy { it }.eachCount().filter { it.value > 1 })
val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana") println(list.groupingBy { it }.eachCount().filter { it.value > 1 }) 

产量

 {apple=2, banana=2}