Hanbit the Developer

Kotlin Documentation | Ordering 본문

Mobile/Kotlin

Kotlin Documentation | Ordering

hanbikan 2023. 5. 24. 14:39

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

문서 링크: https://kotlinlang.org/docs/collection-ordering.html


Natural order

Comparable을 통해 구현된다. 예시는 다음과 같다:

  • 1은 0보다 크다.
  • b는 a보다 크다.

Comparable 인터페이스를 구현하여 compareTo()를 오버라이드 해야 한다. 같은 타입의 객체와 비교하여, 자신의 값이 더 클 경우 양수, 작을 경우 음수, 같을 경우 0을 반환한다.

class Version(val major: Int, val minor: Int): Comparable<Version> {
    override fun compareTo(other: Version): Int = when {
        this.major != other.major -> this.major compareTo other.major // compareTo() in the infix form 
        this.minor != other.minor -> this.minor compareTo other.minor
        else -> 0
    }
}

fun main() {    
    println(Version(1, 2) > Version(1, 3))
    println(Version(2, 0) > Version(1, 5))
}
false
true

정렬은 sorted(), sortedDescending()으로 한다.

Custom orders

어떤 타입과도 비교할 수 있다. 비교 불가능한 객체에 오더링을 하거나, 비교 가능한 타입을 natural order가 아닌 기준으로 오더링 할 수 있다.

구현하기 위해 Comparator를 생성하고 compare() 함수를 오버라이드 해야 한다. 이때 반환되는 정수값은 compareTo()와 동일하게 음수, 0, 양수로 구분되어 해석된다.

val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))
[c, bb, aaa]

또는 Comparator 생성 없이 compareBy()로 간단하게 구현할 수도 있다.

println(listOf("aaa", "bb", "c").sortedWith(compareBy { it.length }))

정렬은 sortedBy(), sortedByDescending()으로 한다.

  • then, thenBy: 같을 경우 또 다른 기준으로 비교
val list = listOf("aa", "b", "bb", "a")

val lengthComparator = compareBy<String> { it.length }
println(list.sortedWith(lengthComparator)) // [b, a, aa, bb]

val lengthThenString = lengthComparator.thenBy { it }
println(list.sortedWith(lengthThenString)) // [a, b, aa, bb]

Reverse order

  • reversed()
  • asReversed(): reversed()와 달리 새 컬렉션 인스턴스를 생성하는 대신, 기존 컬렉션의 뒤집힌 ‘view’를 제공하는 가벼운 방식이다. 이에 따라, 기존 컬렉션의 아이템이 바뀌면 이전에 호출한 asReversed()의 래퍼런스의 값도 변경된다.
    [four, three, two, one]
    [five, four, three, two, one]
    
  • val numbers = mutableListOf("one", "two", "three", "four") val reversedNumbers = numbers.asReversed() println(reversedNumbers) numbers.add("five") println(reversedNumbers)

Random order

val numbers = listOf("one", "two", "three", "four")
println(numbers.shuffled())