0

What is the best way to filter out a list of objects with a list of properties of the given object.

Here is the sample code that shows what I'm trying to achieve:


    data class Person(
            val id: Long = 0,
            val name: String = ""
    )

    fun filterOutList(): List<Person>{

        val idsToRemove = listOf(1, 3)

        val listToFilter = listOf(
                Person(1, "John"),
                Person(2, "Jane"),
                Person(3, "Bob"),
                Person(4, "Nick")
        )

        // expecting to get a list only with Objects that have ids 2 and 4

        return listToFilter.filter { ??? provide `idsToRemove` to get only what was not in the list  }
    }

3 Answers 3

2

Do it this way: return listToFilter.filter { it.id !in idsToRemove }.

To get it compiled, you should explicitly specify the <Long> type parameter when you create idsToRemove: listOf<Long>(1, 3) or listOf(1L, 3L). The compiler infers the <Int> type parameter implicitly.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use native method filter{ }. As following:

return listOf(
                Person(1, "John"),
                Person(2, "Jane"),
                Person(3, "Bob"),
                Person(4, "Nick")
        ).filter{ it.id == 2 || it.id == 4 }

1 Comment

This is kinda hard coding. What if idsToRemove is a dynamic array?
0

I found following solution that worked for me:

val filteredResponse = listToFilter.filter { ! idsToRemove.contains(it.id) }

But as @Bananon mentioned, I had to explicitly specify idsToRemove: listOf<Long>(1, 3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.