[Kotlin] sequence

kimji1
2 min readSep 7, 2020

--

  • Sequences offer the same functions as Iterable but implement another approach to multi-step collection processing.

> Iterable과 동일한 함수를 제공하지만 multi-step collection 처리의 다른 접근법을 구현한다.

  • lazily

Sequence performs all the processing steps one-by-one for every single element. In turn, Iterable completes each step for the whole collection and then proceeds to the next step.

So, the sequences let you avoid building results of intermediate steps, therefore improving the performance of the whole collection processing chain. However, the lazy nature of sequences adds some overhead which may be significant when processing smaller collections or doing simpler computations.

> Sequence는 각 각의 한 요소에 대해 모든 처리 단계를 하나씩 수행한다. Iterable은 각 단계를 전체 컬렉션에 에 대해 완료하고 다음 단계로 넘어간다.

Sequence는 중간 단계 결과물이 생성되는 것을 피할 수 있게 하므로 전체 컬렉션 처리의 성능을 향상시킬 수 있다. 그러나, 작은 컬렉션이나 간단한 계산을 할 때는 큰 overhead가 생길 수 있다.

Iterable

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

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())

--

--

kimji1
kimji1

No responses yet