【问题标题】:Kotlin - how to find number of repeated values in a list?Kotlin - 如何在列表中查找重复值的数量?
【发布时间】:2017-11-09 11:15:48
【问题描述】:

我有一个列表,例如:

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

如何查看苹果在这个列表中重复了多少次?

【问题讨论】:

    标签: functional-programming kotlin


    【解决方案1】:

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

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

    输出

    {apple=2, banana=2}
    

    【讨论】:

    • 如果您不关心哪个索引具有重叠值(例如用于验证),println(list.groupingBy { it }.eachCount().any { it.value > 1 }) 会更有效,因为它会在第一次出现时停止。
    • 我在我的项目中添加了这个扩展功能,用于通过谓词查找 Iterable 中的重复项:inline fun Iterable.findRepeatedItemsBy(crossinline keySelector: (T) -> K) :Map = groupingBy(keySelector) .eachCount() .filter { it.value > 1 }
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2020-09-10
    • 2021-02-28
    • 2015-09-09
    • 2019-11-10
    • 2010-09-08
    • 1970-01-01
    相关资源
    最近更新 更多