ref : https://kotlinlang.org/docs/sequences.html
collection을 이루는 Iterable과 비슷한 역할을 하는 interface
Collection ( 정확하게는 Iterable )에 있는 함수들이 대부분 제공되지만, 실제 구현 방식은 다르게 되어 있다.
JAVA8의 stream과 같은 개념이지만, 자바 예전 버전을 사용하는 경우 stream이 존재하지 않기 때문에, Kotlin에서 자체적으로 지원 해 주는것
Sequence 생성
// From elements
val numbersSequence = sequenceOf("four", "three", "two", "one")
// From Iterable
val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()
// Using generateSequence function
val oddNumbers = generateSequence(1) { it + 2 } // `it` is the previous element
println(oddNumbers.take(5).toList())
//println(oddNumbers.count()) // error: the sequence is infinite
val oddNumbersLessThan10 = generateSequence(1) { if (it < 8) it + 2 else null }
println(oddNumbersLessThan10.count())
Collection
fun checkFlowInIterable() {
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
fun checkFlowInSequence() {
val words = "The quick brown fox jumps over the lazy dog".split(" ")
//convert the List to a Sequence
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")
// terminal operation: obtaining the result as a List
println(lengthsSequence.toList())
}
