To filter items of a set based on a condition in Kotlin, you can use the filter()
function along with a predicate to selectively include items that satisfy the condition.
In this example,
numberSet
with values setOf(1, 2, 3, 4, 5, 6)
.filter()
function on numberSet
to selectively include only the even numbers. We provide a lambda predicate that checks if each number is even using the modulo operator %
.evenNumbers
.fun main() {
val numberSet = setOf(1, 2, 3, 4, 5, 6)
val evenNumbers = numberSet.filter { it % 2 == 0 }
println("Even numbers: $evenNumbers")
}
Even numbers: [2, 4, 6]
In this example,
stringSet
with values setOf("Apple", "Banana", "Apricot", "Orange")
.filter()
function on stringSet
to selectively include only the strings that start with the letter 'A'. We provide a lambda predicate that checks if each string starts with 'A' using the startsWith()
function.filteredStrings
.fun main() {
val stringSet = setOf("Apple", "Banana", "Apricot", "Orange")
val filteredStrings = stringSet.filter { it.startsWith("A") }
println("Strings starting with 'A': $filteredStrings")
}
Strings starting with 'A': [Apple, Apricot]
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Kotlin language with well detailed examples.