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)
}
2条答案
按热度按时间des4xlb01#
您可以对编写的代码进行一点修改,通过检查
ids
是否包含Post
的id
,而不是仅将其与ids
中的第一个值进行比较,来过滤掉单个Post
:此操作的输出为
gfttwv5a2#
您只需要在筛选函数中使用'any'来比较所有列表元素。