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 Execute the above code, and the output is as follows: You can use it. Execute the above code, and the output is as follows: You can use it.
while
loop: 8.36.1. Example #
object Test {
def main(args: Array[String]) {
val it = Iterator("Baidu", "Google", "Runoob", "Taobao")
while (it.hasNext){
println(it.next())
}
}
}
$ scalac Test.scala
$ scala Test
Baidu
Google
Runoob
Taobao
Find the maximum and minimum elements #
it.min
and
it.max
method to find the maximum and minimum elements from the iterator. The example is as follows: 8.36.2. 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 )
}
}
$ scalac Test.scala
$ scala Test
The maximum element is:90
The smallest element is:2
Get the length of the iterator #
it.size
or
it.length
method to see the number of elements in the iterator. Examples are as follows: 8.36.3. 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 )
}
}