Kotlin Set – Filter

To filter elements in a Kotlin Set based on a predicate (condition), call filter() function on this Set and pass the predicate to the filter() function as parameter.

In this tutorial, we will learn how to use filter() function on a Set, to filter its elements based on a condition/predicate.

The syntax to call filter() function on a Set with a predicate is

Set.filter(predicate)

predicate is a lambda function that takes an element of this Set as parameter and returns a boolean value.

Return Value

Set.filter() function returns a List with elements of this Set that satisfied the condition/predicate.

Elements of the Set that return true for the given predicate, make it to the filtered List.

The original Set on which filter() function is called, remains unchanged.

Examples

In the following program, we will take a Set of Integers and filter only odd numbers.

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf(1, 4, 8, 5, 6, 9, 12, 10, 33)
    var filtered = mySet.filter { x -> x % 2 != 0 }
    println("Original Set : ${mySet}")
    println("Filtered     : ${filtered}")
}

Here, the lambda function: { x -> x % 2 != 0 } is the predicate to the filter() function.

For each element x in the Set, only those elements that satisfy the condition x % 2 != 0 are returned in the resulting List.

Output

Original Set : [1, 4, 8, 5, 6, 9, 12, 10, 33]
Filtered     : [1, 5, 9, 33]

In the following example, we will take a Set of Strings, and filter only those strings whose length is equal to 4.

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf("abcd", "xyz", "four", "nice", "cat", "hello")
    var filtered = mySet.filter { x -> x.length == 4 }
    println("Original Set : ${mySet}")
    println("Filtered     : ${filtered}")
}

Output

Original Set : [abcd, xyz, four, nice, cat, hello]
Filtered     : [abcd, four, nice]
ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to filter a Set using a condition/predicate, using filter() function, with the help of examples.