Kotlin으로 안드로이드 프로젝트를 하든 코딩테스트를 준비하든 List를 다루는 일이 많은데 다 기억하기 어려워서 구글링을 자주한다. 자주 쓰는 메서드인데도 불구하고ㅜㅠ🤯
이제라도 제대로 정리하고 외워보려고 작성하는 포스트!👻
List 원본은 변경하지 않고 정렬된 List를 반환한다. (Immutable list 정렬에 사용)
fun <T : Comparable<T>> Array<out T>.sorted(): List<T> fun <T : Comparable<T>> Iterable<T>.sorted(): List<T>
예시)
fun main(args: Array<String>) {
val list = listOf(3, 2, 4, 1, 5)
val sortedList = list.sorted()
println(list) // [3, 2, 4, 1, 5]
println(sortedList) // [1, 2, 3, 4, 5]
}
List 원본 자체를 정렬한다.
fun <T : Comparable<T>> MutableList<T>.sort()
예시)
fun main(args: Array<String>) {
val mutableList = mutableListOf(3, 2, 4, 1, 5)
mutableList.sort()
println(mutableList) // [1, 2, 3, 4, 5]
}
List의 요소가 2개 이상의 데이터 타입으로 이루어져있을 때, seletor를 지정하여 selector 기준으로 정렬한다.
public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit { if (size > 1) sortWith(compareBy(selector)) }
예시)
fun main(args: Array<String>) {
val mutableList = mutableListOf<Pair<Int, Int>>(1 to 3, 4 to 1, 3 to 5)
mutableList.sortBy { it.first }
println(mutableList) // [(1, 3), (3, 5), (4, 1)]
}
새로운 Comparator를 지정하여 그 기준으로 정렬한다.
sortBy와 다른 점은, 다중 기준을 설정할 수 있다는 것이다.
public expect fun <T> Array<out T>.sortWith(comparator: Comparator<in T>): Unit
예시)
fun main(args: Array<String>) {
val mutableList = mutableListOf<Student>()
mutableList.add(Student(1, "김", 20, 1, 3))
mutableList.add(Student(2, "이", 23, 4, 4))
mutableList.add(Student(3, "박", 22, 2, 5))
mutableList.add(Student(4, "최", 26, 4, 5))
// 성적이 높은 순서로 정렬. 단, 성적이 같은 경우 번호가 높은 순서로 정렬.
val result1 = mutableList.sortWith(compareBy<Student> { it.score }.thenBy { it.number }.reversed())
// 성적이 높은 순서로 정렬. 단, 성적이 같은 경우 번호가 낮은 순서로 정렬.
val result2 = mutableList.sortWith(compareBy<Student> { it.score }.reversed().thenBy { it.number })
println(result1) // [Student(number=4, name=최, age=26, grade=4, score=5), Student(number=3, name=박, age=22, grade=2, score=5), Student(number=2, name=이, age=23, grade=4, score=4), Student(number=1, name=김, age=20, grade=1, score=3)]
println(result2) // [Student(number=3, name=박, age=22, grade=2, score=5), Student(number=4, name=최, age=26, grade=4, score=5), Student(number=2, name=이, age=23, grade=4, score=4), Student(number=1,
}
data class Student(val number: Int, val name: String, val age: Int, val grade: Int, val score: Int)