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)
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.