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 properties id and name.
  • We create a list of Person objects with some duplicate entries based on id and name.
  • We use the distinctBy function to get a new list distinctById containing only elements with distinct id.
  • The resulting list distinctById contains elements with id values 1, 2, and 3, with duplicates removed based on id.
  • 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, &quot;John&quot;),
        Person(2, &quot;Jane&quot;),
        Person(1, &quot;John&quot;),
        Person(3, &quot;Alex&quot;)
    )
    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(&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;, &quot;avocado&quot;, &quot;apricot&quot;)
    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.