Kotlin Map asSequence()
Syntax & Examples
Syntax of Map.asSequence()
The syntax of Map.asSequence() extension function is:
fun <K, V> Map<out K, V>.asSequence(): Sequence<Entry<K, V>>
This asSequence() extension function of Map creates a Sequence instance that wraps the original map returning its entries when being iterated.
✐ Examples
1 Map as Sequence of Entries
In this example,
- We create a map named
map1
with integer keys and string values. - We use the
asSequence
extension function to convert the map into a sequence of key-value pairs (entries). - We iterate over the sequence using
forEach
and print each entry to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to "one", 2 to "two", 3 to "three");
val sequence = map1.asSequence();
sequence.forEach { println(it) };
}
Output
1=one 2=two 3=three
2 Map as Sequence of Entries
In this example,
- We create a map named
map2
with string keys and integer values. - We use the
asSequence
extension function to convert the map into a sequence of key-value pairs (entries). - We iterate over the sequence using
forEach
and print each entry to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf("a" to 1, "b" to 2, "c" to 3);
val sequence = map2.asSequence();
sequence.forEach { println(it) };
}
Output
a=1 b=2 c=3
3 Map as Sequence of Entries
In this example,
- We create a map named
map3
with string keys and integer values. - We use the
asSequence
extension function to convert the map into a sequence of key-value pairs (entries). - We iterate over the sequence using
forEach
and print each entry to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 6, "cherry" to 7);
val sequence = map3.asSequence();
sequence.forEach { println(it) };
}
Output
apple=5 banana=6 cherry=7
Summary
In this Kotlin tutorial, we learned about asSequence() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.