Scala Iterator


Release date:2023-11-21 Update date:2023-11-21 Editor:admin View counts:135

Label:

Scala Iterator

Scala Iterator is not a collection, it is a method for accessing the collection.

Iterator it the two basic operations of next and hasNext .

Call it.next() the next element of the iterator is returned and the status of the iterator is updated.

Call it.hasNext() used to detect whether there are any elements in the collection.

The easiest way to get the iterator it to return all elements one by one is to use the while loop:

Example

object Test {
   def main(args: Array[String]) {
      val it = Iterator("Baidu", "Google", "Runoob", "Taobao")

      while (it.hasNext){
         println(it.next())
      }
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
Baidu
Google
Runoob
Taobao

Find the maximum and minimum elements

You can use it. it.min and it.max method to find the maximum and minimum elements from the iterator. The example is as follows:

Example

object Test {
   def main(args: Array[String]) {
      val ita = Iterator(20,40,2,50,69, 90)
      val itb = Iterator(20,40,2,50,69, 90)

      println("The maximum element is:" + ita.max )
      println("The smallest element is:" + itb.min )
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
The maximum element is:90
The smallest element is:2

Get the length of the iterator

You can use it. it.size or it.length method to see the number of elements in the iterator. Examples are as follows:

Example

object Test {
   def main(args: Array[String]) {
      val ita = Iterator(20,40,2,50,69, 90)
      val itb = Iterator(20,40,2,50,69, 90)

      println("The value of ita.size: " + ita.size )
      println("The value of itb.length: " + itb.length )
   }
}

Powered by TorCMS (https://github.com/bukun/TorCMS).