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.
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.
Set.distinct() returns value of type List
.
In Kotlin, we can use the distinct()
function to get a list of distinct elements from a set.
For example,
distinct()
function to get a list of distinct elements from the set.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val distinctNumbers = numbers.distinct()
println("Distinct elements: $distinctNumbers")
}
Distinct elements: [1, 2, 3, 4, 5]
In Kotlin, we can use the distinct()
function to get a list of distinct elements from a set of strings.
For example,
distinct()
function to get a list of distinct elements from the set.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val distinctFruits = fruits.distinct()
println("Distinct fruits: $distinctFruits")
}
Distinct fruits: [apple, banana, cherry]
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,
distinct()
function to get a list of distinct elements from the empty set.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val distinctNumbers = emptySet.distinct()
println("Distinct elements in empty set: $distinctNumbers")
}
Distinct elements in empty set: []
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.