[Kotlin] 코딩테스트 필수 - 정렬

kimgwon·2024년 10월 14일

Kotlin

목록 보기
16/19

sorted()

원본 리스트는 변경되지 않고, 정렬된 결과가 ImmutableList로 반환된다.
sortedDescending()은 내림차순으로 정렬된다.
반환 타입 : ImmutableList

val list = listOf(20, 100, 5, 60, 40)
val sortedList = list.sorted()
val reversedList = list

println("List : $list") // [20, 100, 5, 60, 40]
println("SortedList : $sortedList") // [5, 20, 40, 60, 100]

sort()

MutableList에서 사용하는 메서드로, 원본을 정렬한다.
sortDescending()은 내림차순으로 정렬된다.

val mutableList = mutableListOf(20, 100, 5, 60, 40)
mutableList.sort()

println("MutableList : $mutableList") // [5, 20, 40, 60, 100]

sortedBy()

단일 조건(람다식)에 따라 정렬된 결과가 ImmutableList로 반환된다.
주로 특정 필드나 속성을 기준으로 정렬한다.
sortedByDescending()은 조건에 따라 내림차순으로 정렬된다.
반환 타입: ImmutableList

val people = listOf("Alice", "Bob", "Charlie")
val sortedPeople = people.sortedBy { it.length }
println(sortedPeople)  // 출력: [Bob, Alice, Charlie]

sortBy()

MutableList에서 사용하는 메서드로, 단일 조건에 따라 원본을 정렬한다.
sortByDescending()은 조건에 따라 내림차순으로 정렬된다.

val people = mutableListOf("Alice", "Bob", "Charlie")
people.sortBy { it.length }
println(people)  // 출력: [Bob, Alice, Charlie]

sortedWith()

사용자 정의 Comparator를 사용하여, 조건에 따라 정렬된 결과가 ImmutableList로 반환된다.
주로 다중 조건을 정의한다.
반환 타입 : ImmutableList

val numbers = listOf(3, 1, 4, 1, 5, 9)
val sortedNumbers = numbers.sortedWith(compareBy { it % 2 == 0 })  // 짝수 우선
println(sortedNumbers)  // 출력: [4, 3, 1, 1, 5, 9]
val people = mutableListOf("Alice", "Bob", "Charlie")
people.sortWith(compareBy<String> { it.length }.thenBy { it })  // 길이가 같으면 이름으로 정렬
println(people)  // 출력: [Bob, Alice, Charlie]

sortWith()

사용자 정의 Comparator를 사용하여, 원본을 정렬한다.

val numbers = mutableListOf(3, 1, 4, 1, 5, 9)
numbers.sortWith(compareBy { it % 2 == 0 })  // 짝수 우선
println(numbers)  // 출력: [4, 3, 1, 1, 5, 9]

정리

ed가 붙은 것은 ImmutableList와 MutableList 모두 사용이 가능하다.
ed가 붙지 않은 것은 MutableList에서만 사용 가능하다.
마지막에 Descending을 붙이면 내림차순으로 정렬된다.
sortBy()는 단일 조건 정렬, sortWith()는 다중 조건 정렬에서 사용한다.

0개의 댓글