Kotlin List Distinct - 중복 요소 제거

List.distinct()

List.distinct() 함수를 사용하면 중복된 요소를 제거할 수 있다.

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

    println(list.distinct())
}

Oupput:

[a, b, c]

List.distinctBy()

List.distinctBy() 함수를 사용 요소를 변환하여 그 중복된 값으로 중복을 제거할 수도 있다.

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

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

Oupput:

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

Set

Set는 중복 없이 요소를 저장하는 객체로써, List를 Set으로 변환했다가 다시 List로 변경하면 중복된 요소가 제거된다.

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

    val set = list.toSet()

    val newList = set.toList()

    println(newList)
}

Oupput:

[a, b, c]

참조




최종 수정 : 2021-10-10