Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take nth element of an Iterator

Tags:

scala

I have a scala Iterator[A]. How can I reference the nth element of it?

For instance:

val myIter: Iterator[Seq[String]] = { .... }

//get the size of the Iterator

val s = myIter.size

//get 3rd element (base 0)

val third:Seq[String] = myIter.get(2)  <---- Something like this?

I maybe misreading the docs but can't find a function to do this easily. Thanks for help

like image 267
sectornitad Avatar asked Mar 07 '14 10:03

sectornitad


People also ask

How to get iterator at Nth element of vector?

To get an iterator starting from the n'th item, the idea is to construct an iterator pointing to the beginning of the input vector and call the standard algorithm std::advance to advance the iterator by specified positions.

Can we remove elements using iterator?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

How do you remove an element from a collection using iterator?

Approach 1: Using Iterator The Iterator object is used to iterate over the elements of the list using the hasNext() and next() methods. An if the condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method.


1 Answers

If you want to live dangerously,

myIter.drop(2).next

or if you'd rather be safe

myIter.drop(2).take(1).toList.headOption
like image 62
Rex Kerr Avatar answered Sep 21 '22 08:09

Rex Kerr