To remove elements from a list based on a condition in Kotlin, you can use the `removeIf` method.
In this example,
numbers
with some elements.removeIf
method of the list along with a lambda function to remove elements greater than the threshold.fun main() {
val numbers = mutableListOf(1, 2, 3, 4, 5)
val threshold = 3
numbers.removeIf { it > threshold }
println("Modified list after removing elements greater than $threshold: $numbers")
}
Modified list after removing elements greater than 3: [1, 2, 3]
In this example,
names
with some elements.isLongName
that returns true
if the length of the string is greater than a specified value.removeIf
method of the list along with the isLongName
predicate to remove elements matching the predicate condition.fun main() {
val names = mutableListOf("John", "Alice", "Michael", "Emma")
val maxLength = 5
val isLongName: (String) -> Boolean = { it.length > maxLength }
names.removeIf(isLongName)
println("Modified list after removing long names: $names")
}
Modified list after removing long names: [John, Alice, Emma]
In this tutorial, we learned How to Remove Element from List based on a Condition in Kotlin language with well detailed examples.