Kotlin Set distinct()
Syntax & Examples


Set.distinct() extension function

The distinct() extension function for sets in Kotlin returns a list containing only distinct elements from the set. As sets inherently contain distinct elements, the primary use is to convert the set to a list.


Syntax of Set.distinct()

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

fun <T> Set<T>.distinct(): List<T>

This distinct() extension function of Set returns a list containing only distinct elements from the given set.

Return Type

Set.distinct() returns value of type List.



✐ Examples

1 Using distinct() to get a list of distinct elements from a set

In Kotlin, we can use the distinct() function to get a list of distinct elements from a set.

For example,

  1. Create a set of integers.
  2. Use the distinct() function to get a list of distinct elements from the set.
  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)
    val distinctNumbers = numbers.distinct()
    println("Distinct elements: $distinctNumbers")
}

Output

Distinct elements: [1, 2, 3, 4, 5]

2 Using distinct() with a set of strings

In Kotlin, we can use the distinct() function to get a list of distinct elements from a set of strings.

For example,

  1. Create a set of strings.
  2. Use the distinct() function to get a list of distinct elements from the set.
  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")
    val distinctFruits = fruits.distinct()
    println("Distinct fruits: $distinctFruits")
}

Output

Distinct fruits: [apple, banana, cherry]

3 Using distinct() with an empty set

In Kotlin, we can use the distinct() function to get a list of distinct elements from an empty set, which will result in an empty list.

For example,

  1. Create an empty set of integers.
  2. Use the distinct() function to get a list of distinct elements from the empty set.
  3. Print the resulting list to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val distinctNumbers = emptySet.distinct()
    println("Distinct elements in empty set: $distinctNumbers")
}

Output

Distinct elements in empty set: []

Summary

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