Design Converter
Education
Last updated on Sep 5, 2024
Last updated on Jun 26, 2024
In the Kotlin programming language, filtering collections is a common task when working with lists. Filtering conditions, defined by predicates, are essential in determining which elements are included in the filtered list.
This blog will provide a deep dive into the Kotlin list filter function, explaining its usage, providing code examples, and discussing best practices. We’ll cover how to filter elements based on a given predicate and understand the underlying mechanics.
The filter function in Kotlin is used to filter collection elements based on a given predicate. This function is a part of Kotlin’s standard library and is commonly used in collection processing to retrieve only elements that match specific conditions.
The filter function works by applying a lambda function (or predicate) to each element in the collection. If the predicate returns true, indicating that the element matches the predicate, the element is included in the resulting collection; if it returns false, the element is excluded.
Here's the basic syntax of the filter function:
1fun main() { 2 val numbers = listOf(1, 2, 3, 4, 5, 6) 3 val evenNumbers = numbers.filter { it % 2 == 0 } 4 println(evenNumbers) // Output: [2, 4, 6] 5}
In this example, the filter function checks if each element in the list is even. Only elements that match this given predicate are included in the evenNumbers list.
A predicate is a function that takes a given element and returns a boolean value. The filter function uses this predicate to determine which elements to include in the resulting collection.
Lambda expressions make it easy to write predicates. For example, if you want to filter out numbers greater than 3, you can write:
1fun main() { 2 val numbers = listOf(1, 2, 3, 4, 5) 3 val filteredNumbers = numbers.filter { it > 3 } 4 println(filteredNumbers) // Output: [4, 5] 5}
When filtering collections, you may encounter an empty collection. The filter
function cannot execute the predicate for an empty array element and does not change the original array. The filter
function will return an empty list if no elements match the predicate.
1fun main() { 2 val numbers = listOf(1, 2, 3) 3 val greaterThanFive = numbers.filter { it > 5 } 4 println(greaterThanFive) // Output: [] 5}
You can combine multiple conditions in a single predicate to filter all the elements that match the given criteria using logical operators:
1fun main() { 2 val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9) 3 val filteredNumbers = numbers.filter { it > 2 && it < 8 } 4 println(filteredNumbers) // Output: [3, 4, 5, 6, 7] 5}
Filtering can also be done for negative conditions to exclude elements matching the given criteria:
1fun main() { 2 val numbers = listOf(1, 2, 3, 4, 5) 3 val nonEvenNumbers = numbers.filter { it % 2 != 0 } 4 println(nonEvenNumbers) // Output: [1, 3, 5] 5}
The filter function can be combined with other collection functions like map to perform more complex operations. The original collection remains unchanged after applying the filter function:
1fun main() { 2 val numbers = listOf(1, 2, 3, 4, 5) 3 val filteredMappedNumbers = numbers.filter { it % 2 == 0 }.map { it * 2 } 4 println(filteredMappedNumbers) // Output: [4, 8] 5}
Filtering can be applied to any type of collection, not just numbers:
1fun main() { 2 val words = listOf("apple", "banana", "cherry", "date") 3 val longWords = words.filter { it.length > 5 } 4 println(longWords) // Output: [banana, cherry] 5}
When working with custom objects, you can filter based on specific properties:
1data class Person(val name: String, val age: Int) 2 3fun main() { 4 val people = listOf( 5 Person("Alice", 30), 6 Person("Bob", 20), 7 Person("Charlie", 25) 8 ) 9 val adults = people.filter { it.age >= 21 } 10 println(adults) // Output: [Person(name=Alice, age=30), Person(name=Charlie, age=25)] 11}
The Kotlin list filter function is a powerful tool for filtering collections based on given predicates. By understanding how to use lambda functions and combining filters with other collection operations, you can write concise and efficient Kotlin code. Whether you're filtering a list of numbers, strings, or custom objects, the filter function provides a flexible way to process your data.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.