Kotlin List distinct()
Syntax & Examples


Syntax of List.distinct()

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

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

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



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We apply the distinct() function to list1 to get a new list distinctList containing only unique elements.
  • The resulting list distinctList contains elements 'a', 'p', 'l', 'e', as duplicates are removed.
  • Finally, we print the distinctList to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val distinctList = list1.distinct();
    print(distinctList);
}

Output

[a, p, l, e]

2 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30, 10, 20.
  • We apply the distinct() function to list1 to get a new list distinctList containing only unique elements.
  • The resulting list distinctList contains elements 10, 20, 30, with duplicates removed.
  • Finally, we print the distinctList to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30, 10, 20);
    val distinctList = list1.distinct();
    print(distinctList);
}

Output

[10, 20, 30]

3 Example

In this example,

  • We create a list named list1 containing the strings 'apple', 'banana', 'mango', 'apple', 'banana'.
  • We apply the distinct() function to list1 to get a new list distinctList containing only unique elements.
  • The resulting list distinctList contains elements 'apple', 'banana', 'mango', with duplicates removed.
  • Finally, we print the distinctList to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;, &quot;apple&quot;, &quot;banana&quot;);
    val distinctList = list1.distinct();
    print(distinctList);
}

Output

[apple, banana, mango]

Summary

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