[kotlin/코틀린] Collections(컬렉션) 함수 중 sortedWith과 sortWith 비교

2020. 6. 2. 15:57Android/Kotlin

프로그래머스 코딩 테스트 연습문제 중 "가장 큰 수" 문제를 풀다가 

sortedWith과 sortWith의 차이점이 궁금해져서 쓰게 된 포스팅 

 

먼저 나의 경우에는 IntArray를 String 타입으로 된 리스트로 변경한 다음

첫 번째 요소 + 두 번째 요소와 두 번째 요소  + 첫 번째 요소를 비교하여 내림차순으로 정렬하는 기능이 필요했다 

 

fun solution(numbers: IntArray): String {
        val strings = arrayListOf<String>()

        numbers.forEach {
            strings.add(it.toString())
        }

        /**
         * 첫번째 + 두번째 와 두번째 + 첫번째 값을 비교하여 큰순서대로 정렬
         * 기본 오름차순으로 나오기 때문에 매개변수 순서를 변경하여 내림차순으로 나올수 있도록 한다.
         */
        strings.sortWith(Comparator { t, t2 -> (t2 + t).compareTo(t + t2) })
        
...
}

 

코드 해석 

 

1. add를 이용하여 IntArray()의 요소를 넣을 생각이였기 때문에 String으로 된 리스트를 arrayListOf<String>()으로 선언하고 forEach와 add를 이용하여 Int > Stirng 으로 변환하는 작업을 하였다

 

2. 그 뒤 sortWith함수를 이용하여  조건에 맞게 리스트를 정렬하는 작업을 진행했다 

 

 

그런데 1. 과정을 map을 이용하여 더 간소화할 수 있다는 걸 알게 되었다

fun solution(numbers: IntArray): String {
        val strings = numbers.map { it.toString() }
...
}

이 과정에서 strings의 타입이 ArrayList <String>에서 List <String>가 되고 

이 경우에는 sortWith함수를 사용하지 못한다는 걸 알게 되었다 

Kotlin List는 읽기 전용 액세스만 지원하기 때문에!!!

 

List

interface List<outList <out E> : Collection <E>

A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

 

 

여기서 그럼 코틀린 공식 문서에 sortWith과 sortedWith는 어떻게 정의되어있는지 확인해보자 

 

1. sortWith

sortWith

 

2. sortedWith

sortedWith

 

즉,

sortWith : Comparator에 지정된 순서에 의해 배열을 재 정렬한다 

sortedWith : Comparator에 지정된 순서에 정렬된 배열을 리턴한다 

 

따라서 읽기 전용인 List <String>는 sortWith을 사용하는 대신 sortedWith을 사용하여 새로 정의된 배열을 사용해야 한다 

fun solution(numbers: IntArray): String {
        val strings = numbers.map { it.toString() }
        var newStrings = strings.sortedWith(Comparator { t, t2 -> (t2 + t).compareTo(t + t2) })
...
}

 

 

 

앞으로도 sortWith, sortedWith을 적절하게 잘 사용해야겠다.

 

끝!!