Home > OS >  Kotlin - Filter list with values from another list
Kotlin - Filter list with values from another list

Time:11-03

This is probably super simple but I just cannot figure out how to google for that.

What I have is:

data class Post(val id: String)

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

now I want to filter posts list with the ids list. This is how I filter one id:

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

but how do I filter for all the items in "ids" list?

CodePudding user response:

You can use a small modification of the code you wrote to filter out a single Post by checking if ids contains the id of a Post instead of comparing it only to the first value in 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)
}

The output of this is

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

CodePudding user response:

You just have to use 'any' in your filter function to compare all your list elements.

val output = posts.filter { post -> ids.any { id -> id == post.id } }
  • Related