kotlin filter arraylist
To filter an ArrayList in Kotlin, you can use the filter
function. Here are the steps to filter an ArrayList in Kotlin:
- Create an ArrayList: First, create an ArrayList and populate it with elements. For example, you can create an ArrayList of integers like this:
val numbers = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
- Use the
filter
function: Thefilter
function is used to filter elements based on a condition. It takes a predicate as an argument, which is a lambda expression that specifies the condition for filtering. Here's an example of using thefilter
function to filter out even numbers from the ArrayList:
val evenNumbers = numbers.filter { it % 2 == 0 }
In this example, the lambda expression { it % 2 == 0 }
checks if the element is divisible by 2 (i.e., an even number). If the condition is true, the element is included in the filtered list.
- Retrieve the filtered elements: The
filter
function returns a new list containing the elements that satisfy the condition. You can assign this filtered list to a new variable or use it directly. For example, you can print the filtered list like this:
println(evenNumbers)
This will output the filtered list of even numbers.
That's it! These are the steps to filter an ArrayList in Kotlin using the filter
function.