How to filter elements in an ArrayList in Kotlin
How to filter elements in an ArrayList in Kotlin.
Here is a step-by-step tutorial on how to filter elements in an ArrayList in Kotlin.
Step 1: Create an ArrayList
To start with, you need to create an ArrayList and populate it with some elements. Here's an example of how to create an ArrayList of integers:
val numbers = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Step 2: Filter elements using a predicate
Next, you can filter the elements in the ArrayList based on a given condition or predicate. The filter() function can be used for this purpose. It takes a predicate as an argument, which is a lambda function that specifies the condition for filtering.
val filteredNumbers = numbers.filter { it % 2 == 0 }
In the above example, the lambda function it % 2 == 0 checks if the element is divisible by 2 (i.e., even numbers). The filter() function returns a new list containing only the elements that satisfy the given condition.
Step 3: Print the filtered elements
Finally, you can print the filtered elements from the ArrayList. You can use the forEach() function to iterate over the elements and print them.
filteredNumbers.forEach { println(it) }
This will print all the filtered elements (i.e., even numbers) in the ArrayList.
Complete example: Here's the complete example that demonstrates the filtering of elements in an ArrayList:
fun main() {
val numbers = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val filteredNumbers = numbers.filter { it % 2 == 0 }
filteredNumbers.forEach { println(it) }
}
This will output:
2
4
6
8
10
Conclusion:
In this tutorial, you learned how to filter elements in an ArrayList in Kotlin. By using the filter() function with a predicate, you can easily extract the desired elements from the ArrayList.