To filter elements of an array based on a condition in Kotlin, you can use the filter
method.
In this example,
intArray
with various integer values.filter
method on intArray
to select only the even numbers. The filter
method takes a lambda function that specifies the condition for filtering, in this case, checking if the number is even using the modulus operator %
.filter
method is a list of integers that meet the condition, which we convert to an array using the toTypedArray
method.fun main(args: Array<String>) {
val intArray = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenArray = intArray.filter { it % 2 == 0 }.toTypedArray()
println("Filtered array: ${evenArray.joinToString()}")
}
Filtered array: 2, 4, 6, 8, 10
In this example,
stringArray
with various string values.filter
method on stringArray
to select only the strings that are longer than 3 characters. The filter
method takes a lambda function that specifies the condition for filtering, in this case, checking if the length of the string is greater than 3 using the length
property.filter
method is a list of strings that meet the condition, which we convert to an array using the toTypedArray
method.fun main(args: Array<String>) {
val stringArray = arrayOf("a", "ab", "abc", "abcd", "abcde")
val filteredArray = stringArray.filter { it.length > 3 }.toTypedArray()
println("Filtered array: ${filteredArray.joinToString()}")
}
Filtered array: abcd, abcde
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Kotlin language with well detailed examples.