Kotlin Set filter()
Syntax & Examples


Set.filter() extension function

The filter() extension function for sets in Kotlin returns a list containing only elements of the set that match the given predicate.


Syntax of Set.filter()

The syntax of Set.filter() extension function is:

fun <T> Set<T>.filter(predicate: (T) -> Boolean): List<T>

This filter() extension function of Set returns a list containing only elements matching the given predicate.

Parameters

ParameterOptional/RequiredDescription
predicaterequiredA function that takes an element of the set and returns a Boolean indicating whether the element matches the condition.

Return Type

Set.filter() returns value of type List.



✐ Examples

1 Using filter() to get even numbers from a set

In Kotlin, we can use the filter() function to get a list of even numbers from a set of integers.

For example,

  1. Create a set of integers.
  2. Use the filter() function with a predicate that checks if an element is even.
  3. Print the resulting list to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5, 6)
    val evenNumbers = numbers.filter { it % 2 == 0 }
    println("Even numbers: $evenNumbers")
}

Output

Even numbers: [2, 4, 6]

2 Using filter() to get strings with length greater than 5

In Kotlin, we can use the filter() function to get a list of strings from a set that have a length greater than 5.

For example,

  1. Create a set of strings.
  2. Use the filter() function with a predicate that checks if the length of the string is greater than 5.
  3. Print the resulting list to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry", "date")
    val longFruits = fruits.filter { it.length > 5 }
    println("Fruits with length greater than 5: $longFruits")
}

Output

Fruits with length greater than 5: [banana, cherry]

3 Using filter() with an empty set

In Kotlin, we can use the filter() function on an empty set, which will return an empty list regardless of the predicate.

For example,

  1. Create an empty set of integers.
  2. Use the filter() function with a predicate that checks if an element is positive.
  3. Print the resulting list to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val filteredElements = emptySet.filter { it > 0 }
    println("Filtered elements in empty set: $filteredElements")
}

Output

Filtered elements in empty set: []

Summary

In this Kotlin tutorial, we learned about filter() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.