Hanbit the Developer

Kotlin Documentation | Retrieve collection parts 본문

Mobile/Kotlin

Kotlin Documentation | Retrieve collection parts

hanbikan 2023. 5. 24. 14:19

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

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


Slice

val numbers = listOf("one", "two", "three", "four", "five", "six")    
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))
[two, three, four]
[one, three, five]
[four, six, one]

Take and drop

val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.take(3))
println(numbers.takeLast(3))
println(numbers.drop(1))
println(numbers.dropLast(5))
[one, two, three]
[four, five, six]
[two, three, four, five, six]
[one]
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.takeWhile { !it.startsWith('f') })
println(numbers.takeLastWhile { it != "three" })
println(numbers.dropWhile { it.length == 3 })
println(numbers.dropLastWhile { it.contains('i') })
[one, two, three]
[four, five, six]
[three, four, five, six]
[one, two, three, four]

Chunked

val numbers = (0..13).toList()
println(numbers.chunked(3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]
val numbers = (0..13).toList() 
println(numbers.chunked(3) { it.sum() })  // `it` is a chunk of the original collection
[3, 12, 21, 30, 25]

Windowed

val numbers = listOf("one", "two", "three", "four", "five")    
println(numbers.windowed(2))
[[one, two], [two, three], [three, four], [four, five]]
val numbers = (1..10).toList()
println(numbers.windowed(3, step = 2, partialWindows = true))
println(numbers.windowed(3) { it.sum() })
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]
[6, 9, 12, 15, 18, 21, 24, 27]

*partialWindows: false로 두면 결과에서 [9, 10]이 제거됨

zipWithNext(): Pair로 구성되어 있는 버전의 Windowed

val numbers = listOf("one", "two", "three", "four", "five")    
println(numbers.zipWithNext())
println(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length})