[英]Sorting of scala hashmap using integer key is not working
我正在嘗試使用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,但要謹慎使用。 當status為空列表時,該方法將引發異常。
java.lang.UnsupportedOperationException: empty.minBy
考慮到這一點,也許您可以使用sortBy方法,將其與headOption結合使用:
status.sortBy(_.replaceAll(".*_(\\d+).*", "$1").toInt).headOption
因此,使用給定的數組,結果將是
Some(hdfs://localhost:8020/transactions/transaction_7.txt)
如果數組碰巧是空的,那么您將得到None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.