iterator - Iterating in Scala: checking previous values -


i having following iterator:

val = iterator(("a",5),("a",3),("a",2),("a",1),("b",8),("b",2),("b",1),("c",1)) 

the values inside sorted firstly first element(string) , secondly second(int). how can first 2 values each 'letter'. result should in example:

iterator(("a",5),("a",3),("b",8),("b",2),("c",1)) 

it can done groupby:

it.tolist.groupby(_._1).mapvalues(_.take(2)).values.flatten.toiterator 

but see solution goes through each element , check previous 'string' element , if same , 'count' less 2 yield value.

edit:

following logic of @jwvh answer: how can generalized take first n values instead of first 2?

it might nice if didn't have consume entire iterator @ once.

updated

case class limititr[a,b](var itr: iterator[(a,b)], reps:int) extends iterator[(a,b)] {   private var memory: list[a] = list()   def hasnext = itr.hasnext   def next() = {     val current = itr.next     if (!memory.headoption.contains(current._1))       memory = list()     memory = current._1 :: memory     if (memory.length >= reps) {       itr = itr.dropwhile(_._1 == memory.head)       itr.hasnext  // force iterator forward     }     current   } } 

usage:

val replimiteditr = limititr(itroftuples, numofrepetitionsallowed) 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -