Kotlin list filter

In this guide, we will see how to use the filter() function to filter lists in Kotlin.

What is List Filtering in Kotlin? 

Filtering refers to the process of selecting items from a list that satisfy a given predicate (a function that returns true or false for a given input). In Kotlin, the filter function is employed for this purpose.

Basic Syntax:

fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T>

Examples with Outputs

Basic Filtering 

Filtering out even numbers from a list:

val numbers = listOf(1, 2, 3, 4, 5)
val evens = numbers.filter { it % 2 == 0 }
println(evens)  // Output: [2, 4]

Filtering Based on Index 

Using filterIndexed to filter based on the item and its index:

val letters = listOf('a', 'b', 'c', 'd')
val filtered = letters.filterIndexed { index, char -> index > 1 }
println(filtered)  // Output: [c, d]

Filtering Out Nulls 

Conveniently remove nulls from a list using filterNotNull:

val nullableList = listOf(1, 2, null, 4, null)
val nonNulls = nullableList.filterNotNull()
println(nonNulls)  // Output: [1, 2, 4]

Filtering Using Custom Objects 

Suppose you have a list of Person objects and want to filter by age:

data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 28), Person("Bob", 25), Person("Charlie", 30))
val youngPeople = people.filter { it.age < 29 }
println(youngPeople)  // Output: [Person(name=Alice, age=28), Person(name=Bob, age=25)]

Negated Filtering with filterNot 

Sometimes it's more readable to filter items that don't match a condition:

val items = listOf(1, 2, 3, 4, 5)
val notEvens = items.filterNot { it % 2 == 0 }
println(notEvens)  // Output: [1, 3, 5]

Advanced Examples

Combining Filters 

You can chain multiple filter operations for more complex conditions:

val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val result = numbers.filter { it > 3 }.filter { it % 2 == 0 }
println(result)  // Output: [4, 6, 8]

Using partition for Filter and FilterNot in One 

If you want both filtered and unfiltered results, use partition:

val numbers = listOf(1, 2, 3, 4, 5)
val (evens, odds) = numbers.partition { it % 2 == 0 }
println(evens)  // Output: [2, 4]
println(odds)   // Output: [1, 3, 5]

Conclusion

Kotlin's approach to list filtering epitomizes both clarity and efficiency. Whether you're a seasoned Kotlin developer or just beginning your journey, the provided filter examples are sure to augment your toolkit for list processing. Happy coding!

Related Kotlin Posts

Comments