Scala Iterator slice() method with example

The slice() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class Iterator. It creates a new iterator for the interval given in the slice. The first value present in the slice indicates the start of the element in the new iterator and the second value present in the slice indicates the end.

  • Method Definition:

    def slice(from: Int, until: Int): Iterator[A]

    Where, from implies index of the first element and until implies index of the first element following the slice.

  • Return Type:
    It returns a new iterator with elements from from until until.

Example :



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of slice()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Declaring a iterator
        val iter = Iterator(1, 2, 3, 4, 5)
          
        // Applying slice method
        val iter1 = iter.slice(1, 4)
          
        // Using while loop to print the 
        // elements of new iterator
        while(iter1.hasNext)
        {
              
            // Displays output
            println(iter1.next())
          
        }
    }
}

chevron_right


Output:

2
3
4

Here, if the interval present in the slice is like (n, m) then the elements will be printed from the nth index till (m-1)th index. The functions hasNext and next are used here to print the elements of the new iterator.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of slice()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Declaring a iterator
        val iter = Iterator(2, 4, 5, 6)
          
        // Applying slice method
        val iter1 = iter.slice(0, 3)
          
        // Using while loop to print the 
        // elements of new iterator
        while(iter1.hasNext)
        {
              
            // Displays output
            println(iter1.next())
      
        }
    }
}

chevron_right


Output:

2
4
5

Here, the elements are printed from the index zero till the second index.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.