|
From elements
|
val numbersSequence = sequenceOf("four", "three", "two", "one")
|
let numbersSequence = sequenceOf("four", "three", "two", "one")
|
From Iterable
|
val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()
|
let numbers = listOf("one", "two", "three", "four")
let numbersSequence = numbers.asSequence()
|
From 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
|
let oddNumbers = generateSequence(1) { $0 + 2 } // `it` is the previous element
print(oddNumbers.take(5).toList())
//print(oddNumbers.count()) // error: the sequence is infinite
|
val oddNumbersLessThan10 = generateSequence(1) { if (it + 2 < 10) it + 2 else null }
println(oddNumbersLessThan10.count())
|
let oddNumbersLessThan10 = generateSequence(1) { if ($0 + 2 < 10) $0 + 2 else null }
print(oddNumbersLessThan10.count())
|
From chunks
|
val oddNumbers = sequence {
yield(1)
yieldAll(listOf(3, 5))
yieldAll(generateSequence(7) { it + 2 })
}
println(oddNumbers.take(5).toList())
|
let oddNumbers = sequence {
yield(1)
yieldAll(listOf(3, 5))
yieldAll(generateSequence(7) { $0 + 2 })
}
print(oddNumbers.take(5).toList())
|
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)
|
let words = "The quick brown fox jumps over the lazy dog".split(" ")
let lengthsList = words.filter { print("filter: $it"); it.length > 3 }
.map { print("length: ${it.length}"); it.length }
.take(4)
print("Lengths of first 4 words longer than 3 chars:")
print(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())
|
let words = "The quick brown fox jumps over the lazy dog".split(" ")
//convert the List to a Sequence
let wordsSequence = words.asSequence()
let lengthsSequence = wordsSequence.filter { print("filter: $it"); it.length > 3 }
.map { print("length: ${it.length}"); it.length }
.take(4)
print("Lengths of first 4 words longer than 3 chars")
// terminal operation: obtaining the result as a List
print(lengthsSequence.toList())
|