title: Scala code crashing with java.util.NoSuchElementException: next on empty iterator
body: <p>My code is crashing with java.util.NoSuchElementException: next on empty iterator exception. </p>
  
  <pre><code>def myfunction(arr : Array[(Int,(String,Int))]) = {
  val values = (arr.sortBy(x =&gt; (-x._2._2, x._2._1.head)).toList)
  ...........................
  </code></pre>
  
  <p>The code is crashing in the first line where I am trying to sort an array.</p>
  
  <pre><code>var arr = Array((1,("kk",1)),(1,("hh",1)),(1,("jj",3)),(1,("pp",3)))
  </code></pre>
  
  <p>I am trying to sort the array on the basis of 2nd element of the inner tuple. If there is equality the sort should take place on first element of inner tuple.</p>
  
  <p>output - ((1,("pp",3)),(1,("jj",3)),(1,("hh",1)),(1,("kk",1)))</p>
  
  <p>This is crashing under some scenarios (normally it works fine) which I guess is due to empty array.</p>
  
  <p>How can I get rid of this crash or any other elegant way of achieving the same result.</p>