【问题标题】:Sorting of scala hashmap using integer key is not working使用整数键对 scala hashmap 进行排序不起作用
【发布时间】: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 中有很多方便的方法,并且有很多不同的方法可以达到类似的目的。然而,知道在所有语言中,哈希映射不保持顺序是有用的(除了特殊实现,例如有序但未排序的链接哈希映射)。虽然树图是排序的。这些是不依赖于语言的抽象数据结构。

标签: scala sorting hashmap


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    正如@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

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2017-04-13
      • 1970-01-01
      • 2017-09-22
      相关资源
      最近更新 更多