What if you could pick or skip items from a list with just one simple line of code?
Why Filter and filterNot in Kotlin? - Purpose & Use Cases
Imagine you have a big list of fruits, and you want to pick only the red ones or exclude the green ones. Doing this by checking each fruit one by one and writing separate code for each case can be tiring and confusing.
Manually checking each item means writing lots of repetitive code. It's easy to make mistakes, like forgetting some fruits or mixing conditions. Also, if the list changes, you have to rewrite or fix your code again and again.
Using filter and filterNot lets you quickly and clearly pick items that match or don't match a condition. This makes your code shorter, easier to read, and less error-prone.
val redFruits = mutableListOf<Fruit>() for (fruit in fruits) { if (fruit.color == "red") { redFruits.add(fruit) } }
val redFruits = fruits.filter { it.color == "red" }You can easily create new lists by including or excluding items based on any condition, making data handling smooth and clear.
Suppose you have a list of tasks and want to see only the completed ones or only the ones not done yet. Using filter and filterNot helps you get those lists instantly without extra loops.
Manual filtering is slow and error-prone.
filter and filterNot simplify selecting items by conditions.
They make your code cleaner, shorter, and easier to maintain.