본문 바로가기
Android/Kotlin

[Android/Kotlin] sortWith vs sortedWith: 차이와 사용법

by quessr 2025. 1. 2.

 

코틀린에서는 리스트를 정렬할 때 sortWith와 sortedWith를 자주 사용합니다. 둘은 비슷하게 보이지만, 실제 사용 목적과 동작 방식에서 중요한 차이가 있습니다. 이 글에서는 두 함수의 차이점과 사용 방법에 대해서 정리 해 두겠습니다.

1. sortWith

  • 원본 리스트를 변경하는 함수입니다.
  • MutableList에서만 사용할 수 있습니다.
  • 반환값이 없으며, 리스트 자체를 정렬합니다.

사용 예제

val mutableList = mutableListOf(3, 1, 4, 1, 5, 9)

mutableList.sortWith(compareBy { it }) // 오름차순 정렬
println(mutableList) // 출력: [1, 1, 3, 4, 5, 9]

 

  • compareBy는 정렬 기준을 지정하는 람다를 받아서 처리합니다.
  • 이 경우, 리스트의 원본 데이터(mutableList)가 직접 변경됩니다.

2. sortedWith

  • 새로운 정렬된 리스트를 반환하는 함수입니다.
  • List와 MutableList 모두에서 사용할 수 있습니다.
  • 원본 리스트는 변경되지 않으며, 정렬된 데이터를 반환합니다.

사용 예제

val immutableList = listOf(3, 1, 4, 1, 5, 9)

val sortedList = immutableList.sortedWith(compareBy { it }) // 오름차순 정렬된 새로운 리스트 반환
println(sortedList)  // 출력: [1, 1, 3, 4, 5, 9]
println(immutableList) // 원본은 변경되지 않음: [3, 1, 4, 1, 5, 9]

 

 

3. sortWith vs sortedWith 차이점

특징sortWithsortedWith

동작 방식 원본 리스트를 정렬 정렬된 새로운 리스트를 반환
반환값 없음 (Unit) 정렬된 새로운 리스트 (List<T>)
적용 대상 MutableList List 및 MutableList 모두 가능
원본 데이터 변경 여부 변경됨 변경되지 않음

 

5. 예제: 여러 정렬 조건 사용하기

compareBy를 활용하면 여러 정렬 조건을 손쉽게 지정할 수 있습니다.

val people = listOf(
    Pair(21, "Junkyu"),
    Pair(20, "Sunyoung"),
    Pair(21, "Dohyun"),
    Pair(20, "Choi")
)

val sortedPeople = people.sortedWith(
    compareBy<Pair<Int, String>>(
        { it.first },   // 첫 번째 기준: 나이 (오름차순)
        { it.second }   // 두 번째 기준: 이름 (사전순)
    )
)

println(sortedPeople)
// 출력: [(20, Choi), (20, Sunyoung), (21, Dohyun), (21, Junkyu)]

6. 언제 사용해야 할까?

sortWith를 사용해야 하는 경우

  • 원본 데이터를 그대로 정렬하고 싶을 때 사용합니다.
  • 예를 들어, 정렬된 결과가 이후 코드에서 계속 사용되어야 할 경우:
val mutableList = mutableListOf(3, 1, 4, 1, 5, 9)
mutableList.sortWith(compareByDescending { it }) // 내림차순 정렬
println(mutableList) // 출력: [9, 5, 4, 3, 1, 1]

 

sortedWith를 사용해야 하는 경우

  • 원본 데이터를 유지하면서, 정렬된 데이터를 별도로 사용하거나 반환해야 할 경우:
val immutableList = listOf(3, 1, 4, 1, 5, 9)
val sortedList = immutableList.sortedWith(compareByDescending { it }) // 내림차순 정렬된 새로운 리스트 반환
println(sortedList) // 출력: [9, 5, 4, 3, 1, 1]
println(immutableList) // 원본은 변경되지 않음: [3, 1, 4, 1, 5, 9]

 

5. 성능 비교

  • sortWith: 원본 데이터를 직접 변경하므로 추가적인 리스트를 생성하지 않아 메모리 효율적입니다.
  • sortedWith: 원본 데이터를 유지하며, 새 리스트를 생성하기 때문에 메모리가 더 사용되지만 데이터 안정성을 유지합니다.

요약

  • 데이터가 변경되어도 괜찮다면: sortWith를 사용합니다.
  • 원본 데이터를 유지해야 한다면: sortedWith를 사용합니다.

참고: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/sorted-with.html 

 

sortedWith

Returns a list of all elements sorted according to the specified comparator. The sort is stable. It means that equal elements preserve their order relative to each other after sorting. Since Kotlin1.0 Returns a list of all elements sorted according to the

kotlinlang.org

 

반응형