代码之家  ›  专栏  ›  技术社区  ›  ForeverLearner

使用整数键对scala hashmap排序不起作用

  •  -1
  • ForeverLearner  · 技术社区  · 8 年前

    键是文件号,值是文件名。当我按键对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
            }
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Dima    8 年前

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

    val x = status.minBy { _.replaceAll(".*_(\\d+).*", "$1").toInt }
    
        2
  •  0
  •   GuilleK    8 年前

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

    java.lang.UnsupportedOperationException: empty.minBy
    

    考虑到这一点,也许你可以用 索特比 方法,将其与 头部选项 :

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

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

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

    如果数组恰好是空的,那么您将得到一个 没有

    推荐文章