- Element들을 가져오는데 쓰이는 operator
slice() / take() ... 등을 사용
Slice
- Index를 기반으로 collection을 잘라 새로운 collection을 생성한다.
- range / collection을 인자로 받을 수 있다.
fun sliceCollectionSampleCode() {
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)))
}
Take and drop
- collection의 앞 / 뒤에서 부터 n번째 element 까지 잘라 새로운 collection을 생성하는 operator
fun takeDropSampleCode() {
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))
}
- Boolean 값을 리턴하는 함수와 함께 쓸 수 있음
takeWhile() → element의 조건식이 false가 나오기 전까지 element들을 take ( false가 나온 이후의 element들은 생략 )
takeLastWhile() → collection의 뒤에서 부터 element의 조건식이 false가 나오기 전까지 element들을 take ( false가 나온 이후의 element들은 생략 )
fun takeDropSampleCodeWithPredicates() {
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') })
}
Chunked
- collection을 n개씩 잘라 새로운 collection을 만듬
- n개씩 자르다 남는 마지막 collection의 크기는 n보다 작거나 같음
fun chunkSampleCode() {
val numbers = (0..13).toList()
println(numbers.chunked(3))
}
- chunked된 collection을 transform 할 수 있음
fun chunkWithTransformSampleCode() {
val numbers = (0..13).toList()
println(numbers.chunked(3) { it.sum() }) // `it` is a chunk of the original collection
}
Windowed