Scala 代码因 java.util.NoSuchElementException 崩溃:下一个是空迭代器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28274165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala code crashing with java.util.NoSuchElementException: next on empty iterator
提问by Kundan Kumar
My code is crashing with java.util.NoSuchElementException: next on empty iterator exception.
我的代码因 java.util.NoSuchElementException: next on empty iterator 异常而崩溃。
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)))
输出 - ((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.
我怎样才能摆脱这种崩溃或任何其他实现相同结果的优雅方式。
回答by user5102379
It happens because one of your array items (Int,(String,Int))contains empty string.
发生这种情况是因为您的数组项之一(Int,(String,Int))包含空字符串。
"".head
leads to
造成
java.util.NoSuchElementException: next on empty iterator
java.util.NoSuchElementException:下一个空迭代器
use x._2._1.headOption
利用 x._2._1.headOption
回答by Kundan Kumar
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
从语句中删除 head 是有效的。由于中的空字符串而崩溃 arr
var arr = Array((1,("kk",1)),(1,("hh",1)),(1,("jj",3)),(1,("pp",3)),(1,("",1)))
回答by Andy Liu
I use MLlib in spark and get this error, It turned out that I predict for a non-existing userID or itemID, ALS will generate a matrix for prediction(userIDs * itemIDs), you must make sure that your request is included in this matrix.
我在 spark 中使用 MLlib 并得到这个错误,结果我预测一个不存在的 userID 或 itemID,ALS 将生成一个预测矩阵(userIDs * itemIDs),你必须确保你的请求包含在这个矩阵中.

