조용한 담장

코틀린(Kotlin) Collections : List Specific Operations 본문

kotlin

코틀린(Kotlin) Collections : List Specific Operations

iosroid 2020. 5. 7. 18:08

kotlin

코틀린의 collection 의 List Specific Operations 에 대해 살펴보자.

원문 https://kotlinlang.org/docs/reference/list-operations.html 을 보며 정리.

Retrieving elements by index

index 가 list 의 크기보다 클때 발생하는 exception 을 피하는 함수

getOrElse()

getOrNull()

val numbers = listOf(1, 2, 3, 4)
println(numbers.get(0)) // 1
println(numbers[0]) // 1
//numbers.get(5)                         // exception!
println(numbers.getOrNull(5))             // null
println(numbers.getOrElse(5, {it}))        // 5

Retrieving list parts

subList()

val numbers = (0..13).toList()
println(numbers.subList(3, 6)) // [3, 4, 5]

Finding element positions

Linear search

indexOf()

lastIndexOf()

val numbers = listOf(1, 2, 3, 4, 2, 5)
println(numbers.indexOf(2)) // 1
println(numbers.lastIndexOf(2)) // 4

indexOfFirst()

indexOfLast()

val numbers = mutableListOf(1, 2, 3, 4)
println(numbers.indexOfFirst { it > 2}) // 2
println(numbers.indexOfLast { it % 2 == 1}) // 2

Binary search in sorted lists

binarySearch()

val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println(numbers) // [four, one, three, two]
println(numbers.binarySearch("two"))  // 3
println(numbers.binarySearch("z")) // -5
println(numbers.binarySearch("two", 0, 2))  // -3

Comparator binary search

Comparable list 가 아닌경우 binary search 에 사용하기 위해 Comparator 를 제공한다.

data class Product(val name: String, val price: Double)

val productList = listOf(
    Product("WebStorm", 49.0),
    Product("AppCode", 99.0),
    Product("DotTrace", 129.0),
    Product("ReSharper", 149.0))

println(productList.binarySearch(Product("AppCode", 99.0), compareBy<Product> { it.price }.thenBy { it.name })) // 1

custom comparator

val colors = listOf("Blue", "green", "ORANGE", "Red", "yellow")
println(colors.binarySearch("RED", String.CASE_INSENSITIVE_ORDER)) // 3

Comparison binary search

comparison function 이 0 을 리턴하는 대상을 찾는다.

import kotlin.math.sign
data class Product(val name: String, val price: Double)

fun priceComparison(product: Product, price: Double) = sign(product.price - price).toInt()

fun main() {
    val productList = listOf(
        Product("WebStorm", 49.0),
        Product("AppCode", 99.0),
        Product("DotTrace", 129.0),
        Product("ReSharper", 149.0))

    println(productList.binarySearch { priceComparison(it, 99.0) }) // 1
}

List write operations

Adding

add()

addAll()

val numbers = mutableListOf("one", "five", "six")
numbers.add(1, "two")
numbers.addAll(2, listOf("three", "four"))
println(numbers) // [one, two, three, four, five, six]

Updating

set()

[]

val numbers = mutableListOf("one", "five", "three")
numbers[1] =  "two"
numbers.set(0, "1")
println(numbers) // [1, two, three]

fill()

val numbers = mutableListOf(1, 2, 3, 4)
numbers.fill(3)
println(numbers) // [3, 3, 3, 3]

Removing

removeAt()

val numbers = mutableListOf(1, 2, 3, 4, 3)    
numbers.removeAt(1)
println(numbers) // [1, 3, 4, 3]

Sorting

"sort" 로 시작하는 함수들: sort(), sortDescending(), sortBy(), ...

shuffle()

reverse()

val numbers = mutableListOf("one", "two", "three", "four")

numbers.sort()
println("Sort into ascending: $numbers") // [four, one, three, two]
numbers.sortDescending()
println("Sort into descending: $numbers") // [two, three, one, four]

numbers.sortBy { it.length }
println("Sort into ascending by length: $numbers") // [two, one, four, three]
numbers.sortByDescending { it.last() }
println("Sort into descending by the last letter: $numbers") // [four, two, one, three]

numbers.sortWith(compareBy<String> { it.length }.thenBy { it })
println("Sort by Comparator: $numbers") // [one, two, four, three]

numbers.shuffle()
println("Shuffle: $numbers") // [four, three, two, one]

numbers.reverse()
println("Reverse: $numbers") // [one, two, three, four]

새로운 리스트로 결과를 리턴하는 함수들은 "sorted" 로 시작하거나 "ed/d" 로 끝나는 함수들이다.

sorted(), shuffled(), reversed(), ...

val numbers = mutableListOf("one", "two", "three", "four")
val sorted = numbers.sorted()
println(sorted) // [four, one, three, two]
println(numbers) // [one, two, three, four]
numbers.sort()
println(numbers) // [four, one, three, two]
Comments