The iterator() method is used to iterate a Map.
fun main() { var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language") val iter = x.iterator() while (iter.hasNext()) { val i = iter.next() println(i) } }
Similarly, in the above code we have created a Map using the mapOf() method.
var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
And initialised to the variable x.
Now, to use, iterator() and hasNext(), we have created a variable, iter and initialised with x.iterator().
And internally what happens is, Kotlin would make the Map ready for iteration.
val iter = x.iterator()
And iter variable would contain the values of the Map that can be Iterated.
Then we have used the while loop to Iterate the Map.
while (iter.hasNext()) { val i = iter.next() println(i) }
In the first line of while loop, we have used the hasNext() method. That would check if all the values are Iterated or not.
while (iter.hasNext()) { ... ... }
Once all the values are iterated, the control comes out of the while loop.
Now, the question would be, how does Kotlin understands that all the values of the Map are Iterated.
Well! Thanks to the next() method.
val i = iter.next()
The next() method takes the next value from the iter(iter is holding the Map currently) variable and prints on the screen.
while (iter.hasNext()) { val i = iter.next() println(i) }
Now, if we see the output. Both the key and value is printed as output.
Now, what if, we wanted to print the key only. Or just the value.
We can do that as well. Let us see in the below example.
fun main() { var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language") val iter = x.iterator() while (iter.hasNext()) { val i = iter.next().key println(i) } }
So, if you take a look at the output, only keys are printed.
All thanks to iter.next().key.
val i = iter.next().key
key is a special type of variable that is used with iter.next() to print the key only.
Similarly, let us see how we can print the value only.
fun main() { var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language") val iter = x.iterator() while (iter.hasNext()) { val i = iter.next().value println(i) } }
So, if you take a look at the output, only values are printed.
And this time,
val i = iter.next().value
We have used value variable with iter.next() to print the values.
End