使用整数键对 scala 哈希图进行排序不起作用



我正在尝试使用 scala 中的 HashMap 列出数组对象中的最新文件。 键是文件编号,值是文件名。当我按键对哈希图进行排序时,它似乎总是返回插入的第一个文件名。因此,x 总是返回"hdfs://localhost:8020/transactions/transaction_8.txt"

import scala.collection.mutable.HashMap
import scala.concurrent.Future
import scala.util.matching.Regex
import scala.util.{Failure, Success, Try}
val status = Array("hdfs://localhost:8020/transactions/transaction_8.txt", "hdfs://localhost:8020/transactions/transaction_8.txt", "hdfs://localhost:8020/transactions/transaction_7.txt", "hdfs://localhost:8020/transactions/transaction_10.txt", "hdfs://localhost:8020/transactions/transaction_9.txt")
var x = ""
var newFile: String = ""
val hMap: HashMap[Int, String] = HashMap.empty[Int, String]
if (!status.isEmpty) {
for (e ← status) {
val counter = Try { e.toString.split("_")(1).split("\.")(0) }.getOrElse("1")
hMap.put(counter.toInt, e.toString)
}
x = HashMap(hMap.toSeq.sortWith(_._1 > _._1): _*).head._2
}

你不需要地图,更不用说可变的地图了。也不需要排序。 像这样的事情应该做你想做的事:

val x = status.minBy { _.replaceAll(".*_(\d+).*", "$1").toInt }

正如@Dima所建议的,你可以使用 minBy,但要谨慎使用它。当状态为空列表时,该方法将引发异常。

java.lang.UnsupportedOperationException: empty.minBy

考虑到这一点,也许你可以使用sortBy方法,将其与headOption结合使用:

status.sortBy(_.replaceAll(".*_(\d+).*", "$1").toInt).headOption

因此,使用给定的数组,结果将是

Some(hdfs://localhost:8020/transactions/transaction_7.txt)

如果数组碰巧为空,您最终会得到None

最新更新