4

Behavior of the Iterator size method in Scala

 1 year ago
source link: https://blog.adamgamboa.dev/behavior-of-the-iterator-size-method-in-scala/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Behavior of the Iterator size method in Scala – Adam Gamboa G – DeveloperSkip to content

Adam Gamboa G – Developer

Full Stack notes and tips for developers… Java, React, Kubernetes, Scala, and more…

Advertisements

Iterators are a useful structure to iterate over collections (List, Set, Seq, Map, etc) and access their elements one by one. Two important methods in Scala Iterator are next() and hasNext.

  • hasNext: Indicates if there is another element to return
  • next(): Returns that element.

Iterators are mutable things. You can think of them as pointers. Each time you ask an iterator to give you the next element it points to it will move one position further.

Advertisements

Behavior of the size method

When the size of a iterator is requested, it will traverse each element in the sequence it points to, moving each time one position to the right. When it has no more elements to traverse iterator.hasNext == false it will return the size. But by then it will have exhausted all the elements.

When a new call to size is made, the iterator is already positioned at the end, so it will immediately return 0. Therefore if you tries to iterate your iterator after getting the size of it, you will notice the iterator is not doing anything.

val list = scala.collection.immutable.List(1, 2, 3)
val iterator = list.iterator
println(iterator.size) // 3
println(iterator.hasNext) // false
println(iterator.size) // 0
Scala
val list = scala.collection.immutable.List(1, 2, 3)
val iterator = list.iterator
println(iterator.size) // 3
println(iterator.hasNext) // false
println(iterator.size) // 0

Reference

Post Views: 193
Advertisements

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK