title: Iterating in Scala: checking previous values
body: <p>I am having the following iterator:</p>
  
  <pre><code>val it = Iterator(("a",5),("a",3),("a",2),("a",1),("b",8),("b",2),("b",1),("c",1))
  </code></pre>
  
  <p>The values inside are sorted firstly by the first element(String) and secondly by the second(Int). How can I get the first 2 values from each 'letter'. So the result should be in that example:</p>
  
  <pre><code>Iterator(("a",5),("a",3),("b",8),("b",2),("c",1))
  </code></pre>
  
  <p>It can be done with groupBy:</p>
  
  <pre><code>it.toList.groupBy(_._1).mapValues(_.take(2)).values.flatten.toIterator
  </code></pre>
  
  <p>but I would like to see a solution which goes through each element and check the previous 'string' element and if its the same and the 'count' is less than 2 then it <code>yield</code> this value. </p>
  
  <p><strong>Edit</strong>:</p>
  
  <p>Following the logic of @jwvh answer: How can it be generalized to take the first N values instead of the first 2?</p>