oxbow_lakes - 1 year ago 134
Scala Question

# Scala TreeMap strangeness; implementing a reverse-order ordering

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:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download