简体   繁体   English

如何使用另一个列表的 id 过滤列表?

[英]How to filter a list by using the ids of another list?

I have a list of ids .我有一个ids列表。 I want to filter my list and only keep the values in that list that match the id.我想过滤我的列表,只保留该列表中与 id 匹配的值。

fun filterHelper(ids: List<Int>, list: List<People>) {
     list.filter { ids.contains(it.id) }
}

But this is very inefficient.但这是非常低效的。 It is essentially traversing the list O(n^2).它本质上是遍历列表 O(n^2)。 Does Kotlin let me do better? Kotlin 让我做得更好吗?

I asked a similar question about slicing maps recently.我最近问了一个关于切片地图的类似问题 The answer is that there is no good built-in function, but you can work around by using a Set instead of a List for your ids, which gets you O(1) lookup time for the comparisons, so O(n) in total.答案是没有好的内置 function,但是您可以通过使用Set而不是List作为您的 id 来解决问题,这使您的比较查找时间为 O(1),所以总共 O(n) .

data class People(val id: Int)

fun main() {
    val people = listOf(People(1), People(2), People(3), People(4))
    val ids = setOf(2, 4)

    val filtered = people.filter { it.id in ids }
    println(filtered)
}

Output: Output:

[People(id=2), People(id=4)]

It's worth mentioning that if you already have a list, you can easily convert to a set with:值得一提的是,如果您已经有一个列表,您可以轻松地转换为一个集合:

list.toSet()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM