Scala TreeMap 的奇怪之处;实施逆序排序

发布于 2024-08-13 02:23:33 字数 606 浏览 5 评论 0原文

我有一个 Map[Long, String] 我想按键的降序对其进行迭代。我选择这样做的方式如下:

var m: SortedMap[Long, String] = TreeMap.empty( (l: Long) => -l)
m ++= Map(2L -> "Hello", 1L -> "World", 3L -> "Chris")
println(m) //Map(3 -> Chris, 1 -> World, 2 -> Hello)

我真的不确定我是否理解为什么这不起作用,只能假设我犯了一些愚蠢的错误。当然,以下工作:

var m: SortedMap[Long, String] = TreeMap.empty( (l: Long) => new Ordered[Long] {
  def compare(a: Long) = -l.compare(a)
})
m ++= Map(2L -> "Hello", 1L -> "World", 3L -> "Chris")
println(m) //Map(3 -> Chris, 2 -> Hello, 1 -> World)

I have a Map[Long, String] which I would like iterate over in descending order of the keys. The way I chose to do this was as follows:

var m: SortedMap[Long, String] = TreeMap.empty( (l: Long) => -l)
m ++= Map(2L -> "Hello", 1L -> "World", 3L -> "Chris")
println(m) //Map(3 -> Chris, 1 -> World, 2 -> Hello)

I'm really not sure I understand why this didn't work and can only assume I've made some stupid mistake. Of course the following works:

var m: SortedMap[Long, String] = TreeMap.empty( (l: Long) => new Ordered[Long] {
  def compare(a: Long) = -l.compare(a)
})
m ++= Map(2L -> "Hello", 1L -> "World", 3L -> "Chris")
println(m) //Map(3 -> Chris, 2 -> Hello, 1 -> World)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那小子欠揍 2024-08-20 02:23:33

棘手。让我们进行排序:

scala> (-3L).compare(1L)
res13: Int = -1

scala> (-1L).compare(2L)
res14: Int = -1

因此,我们得出结论 3 < 1 < 2.这就引出了以下问题为什么有效:

def compare(a: Long) = -l.compare(a)

好吧,让我们放一些括号,以确保我们知道我们在做什么

def compare(a: Long) = -(l.compare(a))

好吧,那么答案就很清楚了。您正在反转 compare 的结果,这就是它起作用的原因。这与你第一次做的事情有所不同。

Tricky. Let's run that sorting:

scala> (-3L).compare(1L)
res13: Int = -1

scala> (-1L).compare(2L)
res14: Int = -1

We, therefore, conclude that 3 < 1 < 2. Which begs the question of why the following works:

def compare(a: Long) = -l.compare(a)

Well, let's put some parenthesis there, to make sure we know what we are doing

def compare(a: Long) = -(l.compare(a))

Ok, the answer, then, is clear. You are inverting the result of compare, and that's why it works. It's something different from what you did the first time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文