0
0
Kotlinprogramming~5 mins

Filter and filterNot in Kotlin

Choose your learning style9 modes available
Introduction

Filter and filterNot help you pick items from a list based on a rule. They make it easy to keep or remove items you want.

You want to get only even numbers from a list of numbers.
You want to remove all empty strings from a list of words.
You want to find all students who passed an exam from a list.
You want to exclude all negative numbers from a list.
Syntax
Kotlin
val filteredList = list.filter { item -> condition }
val filteredNotList = list.filterNot { item -> condition }

filter keeps items where the condition is true.

filterNot keeps items where the condition is false.

Examples
This keeps only even numbers from the list.
Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val evens = numbers.filter { it % 2 == 0 }
This removes empty strings from the list.
Kotlin
val words = listOf("apple", "", "banana", "", "cherry")
val nonEmpty = words.filterNot { it.isEmpty() }
Sample Program

This program shows how to use filter and filterNot to split a list based on a condition.

Kotlin
fun main() {
    val numbers = listOf(10, 15, 20, 25, 30)
    val filtered = numbers.filter { it > 20 }
    val filteredNot = numbers.filterNot { it > 20 }
    println("Numbers greater than 20: $filtered")
    println("Numbers NOT greater than 20: $filteredNot")
}
OutputSuccess
Important Notes

Use filter when you want to keep items matching a condition.

Use filterNot when you want to keep items NOT matching a condition.

Both return a new list and do not change the original list.

Summary

filter keeps items where the condition is true.

filterNot keeps items where the condition is false.

They help you easily select or exclude items from collections.