【发布时间】:2019-02-14 06:07:09
【问题描述】:
我正在尝试使用 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
}
【问题讨论】:
-
为什么要将排序后的序列放回不保持顺序的新 HashMap 中。只需改用
x = hMap.toSeq.sortWith(_._1 > _._1).head._2 -
哇。感谢您指出了这一点。当谈到 scala 时,我仍然无法思考。
-
@Tammy Scala 中有很多方便的方法,并且有很多不同的方法可以达到类似的目的。然而,知道在所有语言中,哈希映射不保持顺序是有用的(除了特殊实现,例如有序但未排序的链接哈希映射)。虽然树图是排序的。这些是不依赖于语言的抽象数据结构。