Kotlin List.distinct() – Examples

Kotlin List.distinct()

The Kotlin List.distinct() function returns a list containing only distinct elements from the given list.

Syntax

List.distinct()

Example 1

In this example,

  1. Take a list of strings.
  2. Call distinct() function on the list. The function should return only the distinct elements of the list.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "a", "e", "b", "d", "g", "e")
    val result = list1.distinct()
    print(result)
}

Output

[a, b, c, e, d, g]

Example 2

In this example,

  1. Take a list of integers.
  2. Call distinct() function on the list. The function should return only the distinct elements of the list.

Program

fun main(args: Array<String>) {
    val list1 = listOf(12, 7, 1, 8, 7, 8, 9, 12)
    val result = list1.distinct()
    print(result)
}

Output

[12, 7, 1, 8, 9]