Scala TreeMap 的奇怪之处;实施逆序排序
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
棘手。让我们进行排序:
因此,我们得出结论 3 < 1 < 2.这就引出了以下问题为什么有效:
好吧,让我们放一些括号,以确保我们知道我们在做什么
好吧,那么答案就很清楚了。您正在反转
compare
的结果,这就是它起作用的原因。这与你第一次做的事情有所不同。Tricky. Let's run that sorting:
We, therefore, conclude that 3 < 1 < 2. Which begs the question of why the following works:
Well, let's put some parenthesis there, to make sure we know what we are doing
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.