HTD
Kotlin Documentation | List-specific operations 본문
Category: Standard library - Collections
문서 링크: https://kotlinlang.org/docs/list-operations.html
Retrieve elements by index
- elementAt(), first(), last(), get(), list[index]
- getOrElse(), getOrNull(): 인덱스를 벗어날 경우 예외를 던지지 않고 따로 처리한다:
val numbers = listOf(1, 2, 3, 4)
println(numbers.get(0))
println(numbers[0])
//numbers.get(5) // exception!
println(numbers.getOrNull(5)) // null
println(numbers.getOrElse(5, {it})) // 5
Retrieve list parts
- subList()
val numbers = (0..13).toList()
println(numbers.subList(3, 6))
[3, 4, 5]
Find element positions
- indexOf(), lastIndexOf(): 해당하는 원소가 없을 경우 -1을 반환한다.
val numbers = listOf(1, 2, 3, 4, 2, 5)
println(numbers.indexOf(2))
println(numbers.lastIndexOf(2))
1
4
- indexOfFirst(), indexOfLast(): predicate를 기준으로 검색한다.
val numbers = mutableListOf(1, 2, 3, 4)
println(numbers.indexOfFirst { it > 2})
println(numbers.indexOfLast { it % 2 == 1})
Binary search in sorted lists
- binarySearch(): 정렬된 리스트에 대해서 이진탐색을 수행한다. 원소가 없을 경우, (-insertPoint - 1)를 반환한다. 이때 insertPoint는, 검색 대상 원소를 삽입했을 때 정렬된 순서가 유지되는 인덱스를 말한다.
- 음수인 이유: 찾지 못했다는 정보를 전달하기 위해
- -1을 해주는 이유: -1을 붙이지 않았다고 하면, 0이 반환되면 탐색이 성공(+0)한 건지 실패(-0)한 건지 판단할 수 없음
- *(-insertPoint - 1)에 대한 개인적인 추측:
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println(numbers)
println(numbers.binarySearch("two")) // 3
println(numbers.binarySearch("z")) // -5
println(numbers.binarySearch("two", 0, 2)) // -3
[four, one, three, two]
3
-5
-3
Comparator binary search
원소가 Comparable이 아닐 때, Comparator를 제공할 수 있다.
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 }))
Custom comparator:
val colors = listOf("Blue", "green", "ORANGE", "Red", "yellow")
println(colors.binarySearch("RED", String.CASE_INSENSITIVE_ORDER)) // 3
Comparison binary search
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) })
}
List write operations
- add()
- this[1] = “two”
- fill()
[3, 3, 3, 3]
- val numbers = mutableListOf(1, 2, 3, 4) numbers.fill(3) println(numbers)
- removeAt()
- ed/d suffix for immutable collection: sort() & sorted(), shuffle() & shuffled(), reverse() & reversed()
- asReversed(): 원본의 reversed view를 제공하기 때문에, 변경할 경우 원본에 영향을 미친다.
'Kotlin' 카테고리의 다른 글
Kotlin Documentation | Map-specific operations (0) | 2023.05.24 |
---|---|
Kotlin Documentation | Set-specific operations (0) | 2023.05.24 |
Kotlin Documentation | Write operations (0) | 2023.05.24 |
Kotlin Documentation | Aggregate operations (0) | 2023.05.24 |
Kotlin Documentation | Ordering (0) | 2023.05.24 |