【发布时间】:2014-02-28 08:13:57
【问题描述】:
该函数统计List中指定位置的单词个数,并输出一个Map,其中包含该单词以及该单词在List中被提及的次数:
def getTopLinks(data: List[String], positionOfElementToCount: Int) = {
val words = data.map(d => d.split(",")(positionOfElementToCount).trim)
val wordCount: Map[String, Int] = words.foldLeft(Map.empty[String, Int]) { (m, x) => m + ((x, m.getOrElse(x, 0) + 1)) }
val sortedWordCount = wordCount.toList.sortBy { _._2 }.reverse
sortedWordCount
}
此方法抛出 java.lang.ArrayIndexOutOfBoundsException 。但是我怎么能在上面的函数中忽略这个异常。如果 List 中的元素引发异常,则忽略它并继续。我认为我不能在行 val words = data.map(d => d.split(",")(positionOfElementToCount).trim) 周围包装一个 try catch,因为这样我就无法继续处理,因为在某处抛出异常在此声明中。
如果这个过程发生在一个 for 循环中,那么我可以在有问题的行周围包裹一个 try catch 并继续,但我认为在这种情况下我不能这样做?
【问题讨论】:
标签: scala