Sequence는 필요할 때 요소를 생성하여 처리한다.
하지만 간단한 연산이나 작은 컬렉션의 경우에는 시퀀스의 오버헤드가 더 커질 수 있으므로, 상황에 따라 선택하는 것이 중요하다.
val numbersSequence = sequenceOf("four", "three", "two", "one")
val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()
val oddNumbers = generateSequence(1) { it + 2 }
println(oddNumbers.take(5).toList()) // [1, 3, 5, 7, 9]
val oddNumbers = sequence {
yield(1)
yieldAll(listOf(3, 5))
yieldAll(generateSequence(7) { it + 2 })
}
println(oddNumbers.take(5).toList()) // [1, 3, 5, 7, 9]
Iterable은 filter와 map 함수가 순서대로 실행된다. 모든 요소에 대해 filter가 실행된 후, 남은 요소에 대해 map이 실행된다.
val words = "The quick brown fox jumps over the lazy dog".split(" ")
val lengthsList = words.filter { println("filter: $it"); it.length > 3 }
.map { println("length: ${it.length}"); it.length }
.take(4)
println("Lengths of first 4 words longer than 3 chars:")
println(lengthsList)
Sequence는 filter와 map이 각 요소에 대해 하나씩 순차적으로 실행된다. take(4)로 인해 4개의 요소만 처리된 후 종료된다.
val words = "The quick brown fox jumps over the lazy dog".split(" ")
val wordsSequence = words.asSequence()
val lengthsSequence = wordsSequence.filter { println("filter: $it"); it.length > 3 }
.map { println("length: ${it.length}"); it.length }
.take(4)
println("Lengths of first 4 words longer than 3 chars")
println(lengthsSequence.toList())