The distinctBy() extension function for sets in Kotlin returns a list containing only elements from the set that have distinct keys returned by the given selector function.
The syntax of Set.distinctBy() extension function is:
fun <T, K> Set<T>.distinctBy(selector: (T) -> K): List<T>
This distinctBy() extension function of Set returns a list containing only elements from the given set having distinct keys returned by the given selector function.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element of the set and returns a key used for determining distinct elements. |
Set.distinctBy() returns value of type List
.
In Kotlin, we can use the distinctBy()
function to get a list of distinct elements from a set of strings based on their length.
For example,
distinctBy()
function with a selector function that returns the length of each string.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date")
val distinctByLength = fruits.distinctBy { it.length }
println("Distinct fruits by length: $distinctByLength")
}
Distinct fruits by length: [apple, banana, date]
In Kotlin, we can use the distinctBy()
function to get a list of distinct elements from a set of strings based on their first character.
For example,
distinctBy()
function with a selector function that returns the first character of each string.println
function.fun main(args: Array<String>) {
val words = setOf("apple", "apricot", "banana", "blueberry")
val distinctByFirstChar = words.distinctBy { it.first() }
println("Distinct words by first character: $distinctByFirstChar")
}
Distinct words by first character: [apple, banana]
In Kotlin, we can use the distinctBy()
function to get a list of distinct elements from an empty set based on a given selector function, which will result in an empty list.
For example,
distinctBy()
function with a selector function that returns the integer itself.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val distinctNumbers = emptySet.distinctBy { it }
println("Distinct elements in empty set: $distinctNumbers")
}
Distinct elements in empty set: []
In this Kotlin tutorial, we learned about distinctBy() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.