Kotlin List distinctBy()
Syntax & Examples
Syntax of List.distinctBy()
The syntax of List.distinctBy() extension function is:
fun <T, K> Iterable<T>.distinctBy( selector: (T) -> K ): List<T>
This distinctBy() extension function of List returns a list containing only elements from the given collection having distinct keys returned by the given selector function.
✐ Examples
1 Example
In this example,
- We define a data class
Person
with propertiesid
andname
. - We create a list of
Person
objects with some duplicate entries based onid
andname
. - We use the
distinctBy
function to get a new listdistinctById
containing only elements with distinctid
. - The resulting list
distinctById
contains elements withid
values1
,2
, and3
, with duplicates removed based onid
. - Finally, we print the
distinctById
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val id: Int, val name: String)
val list = listOf(
Person(1, "John"),
Person(2, "Jane"),
Person(1, "John"),
Person(3, "Alex")
)
val distinctById = list.distinctBy { it.id }
print(distinctById)
}
Output
[Person(id=1, name=John), Person(id=2, name=Jane), Person(id=3, name=Alex)]
2 Example
In this example,
- We create a list of strings containing various fruits.
- We apply the
distinctBy
function with a selector function that returns the length of each string. - The resulting list
distinctByLength
contains only elements with distinct lengths. - Finally, we print the
distinctByLength
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "mango", "avocado", "apricot")
val distinctByLength = list.distinctBy { it.length }
print(distinctByLength)
}
Output
[apple, banana, avocado]
3 Example
In this example,
- We create a list of integers.
- We apply the
distinctBy
function with a selector function that returns the remainder of each number when divided by 5. - The resulting list
distinctByMod5
contains only elements with distinct remainders when divided by 5. - Finally, we print the
distinctByMod5
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 17, 20, 25, 30, 35)
val distinctByMod5 = list.distinctBy { it % 5 }
print(distinctByMod5)
}
Output
[10, 17]
Summary
In this Kotlin tutorial, we learned about distinctBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.