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

╄→гoц情女王★ 提交于 2020-08-21 05:02:21

问题


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?


回答1:


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




回答2:


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}


来源:https://stackoverflow.com/questions/47200440/kotlin-how-to-find-number-of-repeated-values-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!