gpt4 book ai didi

Kotlin - 使用另一个列表中的值过滤列表

转载 作者:行者123 更新时间:2023-12-02 18:01:28 25 4
gpt4 key购买 nike

这可能非常简单,但我就是不知道如何用谷歌搜索。

我有的是:

data class Post(val id: String)

val ids = listOf("1", "5", "19")
val posts = listOf<Post>(post1, post2, post3 etc)

现在我想用 ids 列表过滤帖子列表。这是我过滤一个 id 的方式:

val output = posts.filter{ it.id == ids[0]}

但我如何过滤“ids”列表中的所有项目?

最佳答案

您可以通过检查 ids 是否包含某个帖子的 id 来对您编写的代码进行少量修改,以过滤掉单个 Post Post 而不是仅将其与 ids 中的第一个值进行比较:

fun main() {
// list of ids to be filtered
val ids = listOf("1", "5", "19")
// list of posts to filter from
val posts = listOf(
Post("1"), Post("2"),
Post("3"), Post("5"),
Post("9"), Post("10"),
Post("15"), Post("19"),
Post("20")
)
// filter a single post that matches the first id from ids
val singleOutput = posts.filter { it.id == ids[0] }
// filter all posts that have an id contained in ids
val multiOutput = posts.filter { ids.contains(it.id) }
// print the single post with the matching id
println(singleOutput)
// print the list of posts with matching ids
println(multiOutput)
}

这个的输出是

[Post(id=1)]
[Post(id=1), Post(id=5), Post(id=19)]

关于Kotlin - 使用另一个列表中的值过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74285172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com