Removing Duplicate Elements with Kotlin List Distinct

List.distinct()

You can remove duplicate elements by using the List.distinct() function.

fun main() {
    val list = listOf('a', 'b', 'c', 'a', 'c')

    println(list.distinct())
}

Output:

[a, b, c]

List.distinctBy()

You can also use the List.distinctBy() function to transform elements and remove duplicates based on the transformed values.

fun main() {
    val list = listOf('a', 'A', 'b', 'B', 'c', 'A', 'a', 'C')

    println(list.distinct())
    println(list.distinctBy { it.uppercaseChar() })
}

Output:

[a, A, b, B, c, C]
[a, b, c]

Set

Set is an object that stores elements without duplicates. If you convert a List to a Set and then back to a List, duplicate elements are removed.

fun main() {
    val list = listOf('a', 'b', 'c', 'a', 'c')

    val set = list.toSet()

    val newList = set.toList()

    println(newList)
}

Output:

[a, b, c]

References