To remove items from a set based on a condition in Kotlin, you can use the removeIf()
method available for mutable sets.
In this example,
numberSet
with values val numberSet = mutableSetOf(1, 2, 3, 4, 5)
.removeIf()
method on numberSet
to remove even numbers.removeIf()
method removes elements from the set for which the given predicate returns true
.%
operator.fun main() {
val numberSet = mutableSetOf(1, 2, 3, 4, 5)
println("Original Set: $numberSet")
numberSet.removeIf { it % 2 == 0 }
println("Set after removing even numbers: $numberSet")
}
Original Set: [1, 2, 3, 4, 5] Set after removing even numbers: [1, 3, 5]
In this example,
stringSet
with values val stringSet = mutableSetOf("apple", "banana", "orange", "kiwi")
.removeIf()
method on stringSet
to remove strings longer than 4 characters.removeIf()
method removes elements from the set for which the given predicate returns true
.length
property.fun main() {
val stringSet = mutableSetOf("apple", "banana", "orange", "kiwi")
println("Original Set: $stringSet")
stringSet.removeIf { it.length > 4 }
println("Set after removing strings longer than 4 characters: $stringSet")
}
Original Set: [apple, banana, orange, kiwi] Set after removing strings longer than 4 characters: [kiwi, apple]
In this tutorial, we learned How to Remove Items from Set based on a Condition in Kotlin language with well detailed examples.