Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

How to use iterators in Scala

Sheza Munir

Iterators allow the user to access elements in a collection one by one. They are very beneficial when the data being processed is large and cannot be accessed all at once.

We usually use the keyword it to refer to an iterator.

Methods

Common methods associated with iterators are next and hasNext. it.hasNext checks if there is an element after the current one in the collection. it.next returns the next element.

Declaration

There are two ways to declare an iterator:

  1. Direct: While declaring the collection, put it in parentheses with the iterator keyword.
val it = Iterator(1, 2, 3, 4, 5)
  1. Indirect: The collection is declared first, and then connected with the iterator.
val v = List(1, 2, 3, 4, 5)
val it = v.iterator

Usage with loops

We commonly use iterators with loops to step through the collection. The most common loop with iterators is the while loop, which runs until there is a next element (condition checks for it.hasNext).

Code

The following code shows the implementation of iterators in Scala:

object Main extends App{
  // direct declaration of iterator
  val it_1 = Iterator(1, 2, 3, 4, 5)

  //iterating through the collection
  while(it_1.hasNext)
  {
      println (it_1.next)
  }

  //indirect declaration of iterator
  val v = List(6, 7, 8, 9, 10)
  val it_2 = v.iterator

  //iterating through the collection
  while(it_2.hasNext)
  {
      println (it_2.next)
  }

  // using for loop with iterator 
  val it_3 = Iterator(11, 12, 13, 14, 15)
  for(k <- it_3) println(k)
  
}

RELATED TAGS

scala

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring