코틀린은 정렬 함수가 너무너무너무 많아서 한번 정리할 필요가 있어 그 내용을 정리해봤다!
기본적인 것은 sort(), sorted(), sortWith(), sortedWith(), sortBy(), sortedBy()가 있고 배열에서 쓸 수 있는것도 있다.
일단 차근차근 하나하나씩 적어보자.
1) sort()
- 원본 자체의 요소들을 정렬하기 때문에 배열이나 mutableList를 정렬한다.
배열 -> sort()
배열의 경우 fromIndex ~ toIndex까지 정렬을 설정할 수 있음!
mutableList -> sort()
2) sorted()
- 모든 Iterable 객체와 배열 사용 가능
- 원본 객체는 그대로 두고 원본을 복제한 새로운 리스트를 정렬하여 반환한다.
배열 -> sorted()
원시배열 -> sorted()
Iterable -> sorted()
3) sortedArray()
- 정렬된 배열을 반환
- 원본 배열은 그대로 두고 원본을 복제한 새로운 배열을 정렬하여 반환한다.
4) sort(), sorted(), sortedArray() 내림차순
sort() -> sortDescending()
sorted() -> sortedDescending()
sortedArray() -> sortedArrayDescending()
5) sortWith(), sortedWith()
- sortBy()는 내부에 여러 객체를 갖고 있는 타입일 때, 어떤 객체를 비교할지 선택하여 정렬할 경우 사용한다.
- sortBy() -> mutable
- sortedBy() -> Iterable
data class Person(
val name : String,
val age : Int,
val sex : Boolean
)
fun main(){
val person = listOf(Person("a",20,true),Person("b",28,true),Person("c",25,true))
println(person.sortedBy { it.age })
}
//[Person(name=a, age=20, sex=true), Person(name=c, age=25, sex=true),Person(name=b, age=28, sex=true)]
내림 차순의 경우 Descending을 붙여주면 된다
- sortBy() -> sortByDescending()
- sortedBy() -> sortedByDescending()
6) sortWith(), sortedWith()
- 기준이 2개 이상일 경우 사용한다.
- 인자로 Comparator를 구현하여 넘겨주면 되는데 이때 thenBy를 사용하여 두 번째 기준을 세울 수 있다.
- sortWith() -> mutableList
- sortedWith() -> iterable
data class Person(
val name : String,
val age : Int,
)
fun main(){
val person = mutableListOf(Person("a",20),Person("c",28),Person("b",28),Person("c",25))
person.sortWith(compareBy<Person>{
it.age
}.thenBy {
it.name
})
println(person)
}
// [Person(name=a, age=20), Person(name=c, age=25), Person(name=b, age=28), Person(name=c, age=28)]
내림 차순의 경우에는 아래와 같이 변경해주면 된다.
- compareBy -> compareByDescending
- thenBy -> thenByDescending
'Language > kotlin' 카테고리의 다른 글
[Kotlin] Coroutine (0) | 2024.07.23 |
---|---|
[Kotlin] 스코프함수(Scope function) (1) | 2024.07.05 |
[Kotlin] 추상 클래스 & 인터페이스 (0) | 2024.06.10 |
[kotlin] Data class 란? (0) | 2024.05.29 |
[kotlin] 배열 (0) | 2023.12.15 |