The syntax of Map.asIterable() extension function is:
fun <K, V> Map<out K, V>.asIterable(): Iterable<Entry<K, V>>
This asIterable() extension function of Map creates an Iterable instance that wraps the original map returning its entries when being iterated.
In this example,
map1
containing pairs of numbers and characters.map1
to an iterable using the asIterable()
function.forEach
and print each entry to standard output.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val iterable1 = map1.asIterable()
iterable1.forEach { println(it) }
}
1=a 2=b 3=c
In this example,
map2
containing pairs of characters and numbers.map2
to an iterable using the asIterable()
function.forEach
and print each entry to standard output.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val iterable2 = map2.asIterable()
iterable2.forEach { println(it) }
}
a=1 b=2 c=3
In this example,
map3
containing pairs of strings and numbers.map3
to an iterable using the asIterable()
function.forEach
and print each entry to standard output.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val iterable3 = map3.asIterable()
iterable3.forEach { println(it) }
}
apple=1 banana=2 cherry=3
In this Kotlin tutorial, we learned about asIterable() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.