Copilot Kotlin: Filter arrays
Video: Copilot Kotlin: Filter arrays by Taught by Celeste AI - AI Coding Coach
Watch full page →Copilot Kotlin: Filter Arrays
Filtering arrays is a common operation in Kotlin to create a new list containing only elements that satisfy a given condition. Using Kotlin's built-in filter function, you can write concise and readable code to extract elements based on predicates.
Code
// Define an array of integers
val numbers = arrayOf(1, 2, 3, 4, 5, 6)
// Filter to get only even numbers
val evenNumbers = numbers.filter { it % 2 == 0 }
// Print the filtered list
println(evenNumbers) // Output: [2, 4, 6]
Key Points
- Kotlin's
filterfunction returns a list containing elements that match the given predicate. - The predicate is a lambda expression that evaluates each element to a Boolean.
- Filtering does not modify the original array, it creates a new collection.
- You can filter arrays, lists, and other collections in Kotlin using the same
filtermethod.