Kotlin Map asIterable()
Syntax & Examples


Syntax of Map.asIterable()

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.



✐ Examples

1 Iterate over entries in map of numbers and characters

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We then convert map1 to an iterable using the asIterable() function.
  • We iterate over each entry in the iterable using forEach and print each entry to standard output.

Kotlin Program

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

Output

1=a
2=b
3=c

2 Iterate over entries in map of characters and numbers

In this example,

  • We create a map named map2 containing pairs of characters and numbers.
  • We then convert map2 to an iterable using the asIterable() function.
  • We iterate over each entry in the iterable 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 iterable2 = map2.asIterable()
    iterable2.forEach { println(it) }
}

Output

a=1
b=2
c=3

3 Iterate over entries in map of strings and numbers

In this example,

  • We create a map named map3 containing pairs of strings and numbers.
  • We then convert map3 to an iterable using the asIterable() function.
  • We iterate over each entry in the iterable using forEach and print each entry to standard output.

Kotlin Program

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

Output

apple=1
banana=2
cherry=3

Summary

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.