Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala code crashing with java.util.NoSuchElementException: next on empty iterator

My code is crashing with java.util.NoSuchElementException: next on empty iterator exception.

def myfunction(arr : Array[(Int,(String,Int))]) = {
val values = (arr.sortBy(x => (-x._2._2, x._2._1.head)).toList)
...........................

The code is crashing in the first line where I am trying to sort an array.

var arr = Array((1,("kk",1)),(1,("hh",1)),(1,("jj",3)),(1,("pp",3)))

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.

output - ((1,("pp",3)),(1,("jj",3)),(1,("hh",1)),(1,("kk",1)))

This is crashing under some scenarios (normally it works fine) which I guess is due to empty array.

How can I get rid of this crash or any other elegant way of achieving the same result.

like image 324
Kundan Kumar Avatar asked Feb 02 '15 09:02

Kundan Kumar


2 Answers

It happens because one of your array items (Int,(String,Int)) contains empty string.

"".head

leads to

java.util.NoSuchElementException: next on empty iterator

use x._2._1.headOption

like image 137
user5102379 Avatar answered Oct 22 '22 20:10

user5102379


val values = (arr.sortBy(x => (-x._2._2, x._2._1)).toList)

Removing head from the statement works.This crashes because of the empty string in arr

var arr = Array((1,("kk",1)),(1,("hh",1)),(1,("jj",3)),(1,("pp",3)),(1,("",1)))
like image 4
Kundan Kumar Avatar answered Oct 22 '22 19:10

Kundan Kumar