0
0
KotlinHow-ToBeginner · 3 min read

How to Filter List in Kotlin: Simple Guide with Examples

In Kotlin, you can filter a list using the filter function by passing a condition inside a lambda. This returns a new list containing only the elements that match the condition.
📐

Syntax

The filter function takes a lambda expression that defines the condition to keep elements in the list. It returns a new list with elements where the condition is true.

  • list.filter { condition }: Filters elements based on the condition.
  • The lambda receives each element as it by default.
  • Returns a new list without changing the original.
kotlin
val filteredList = list.filter { it > 5 }
💻

Example

This example shows how to filter a list of numbers to keep only those greater than 5.

kotlin
fun main() {
    val numbers = listOf(1, 3, 6, 8, 2, 10)
    val filtered = numbers.filter { it > 5 }
    println(filtered)
}
Output
[6, 8, 10]
⚠️

Common Pitfalls

One common mistake is trying to filter the list without returning a Boolean condition inside the lambda. Another is expecting filter to modify the original list, but it always returns a new list.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4)
    // Wrong: lambda does not return a Boolean
    // val wrongFilter = numbers.filter { println(it) } // This causes a compile error

    // Correct: return a Boolean condition
    val correctFilter = numbers.filter { it % 2 == 0 }
    println(correctFilter) // Output: [2, 4]
}
Output
[2, 4]
📊

Quick Reference

FunctionDescriptionExample
filterReturns a list of elements matching the conditionlist.filter { it > 5 }
filterNotReturns elements NOT matching the conditionlist.filterNot { it > 5 }
filterIndexedFilters with element index and valuelist.filterIndexed { index, value -> index % 2 == 0 }

Key Takeaways

Use filter with a lambda returning a Boolean to select list elements.
filter returns a new list and does not change the original list.
The lambda parameter it represents each element in the list.
Common mistake: forgetting to return a Boolean condition inside the lambda.
Use filterNot to get elements that do not match the condition.