Issue with Scala Size and take command

scala

#1

Team,

I am currently following the youtube series for scala ( https://www.youtube.com/watch?v=Iz74aWSnb5c&list=PLf0swTFhTI8qtOLP5rWmwonnlilIBIrsl&index=15 )

URL: http://www.itversity.com/topic/exercise-scala-collections

I have imported the ls2014.tsv file which contains the election result and getting the below error.


scala> import scala.io.Source
import scala.io.Source

scala> val fn="/home/thinksathya/sathya/ls2014.tsv"
fn: String = /home/thinksathya/sathya/ls2014.tsv

scala> val a = Source.fromFile(fn).getLines
a: Iterator[String] = non-empty iterator

scala> a.size
res8: Int = 8356

scala> a.size
res9: Int = 0

scala>


When I provide the a.size command twice all the data are getting deleted. Could you help me with this issue.

While calculating Nota, if I give take command or size command all the data are getting deleted.

Also while looking for group by it gives Out of Bound exception.

To brief, while providing the take or size command all the data are getting deleted and have to start from the first each time.

Thanks
Sathya


#2

Iterators are data structures that allows to iterate over a sequence of elements. They have a hasNext method for checking if there is a next element available, once the element is returned it will discard from the iterator. So, if you want to reuse the iterator again then you have to regenerate the iterator.


#3

Thanks Sunil.

My question now is, do I need to start from the first if I have to use the size and take command ?

Thanks
Sathya


#4

val a = Source.fromFile(fn).getLines

You have to keep on generating the iterator if you want to print the output