0
0
Kotlinprogramming~3 mins

Why Filter and filterNot in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could pick or skip items from a list with just one simple line of code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
val redFruits = mutableListOf<Fruit>()
for (fruit in fruits) {
  if (fruit.color == "red") {
    redFruits.add(fruit)
  }
}
After
val redFruits = fruits.filter { it.color == "red" }
What It Enables

You can easily create new lists by including or excluding items based on any condition, making data handling smooth and clear.

Real Life Example

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.

Key Takeaways

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.