Sorting maps in Scala.

697 views
Skip to first unread message

Jetinder Rathore

unread,
Aug 20, 2013, 9:25:53 AM8/20/13
to scala...@googlegroups.com
Hi,

I have a map: 

Map("z"->2, "c"->1, "b"->3, "a"->2, "t"-> 5)

i want to sort the map based on both keys and values- first values(descending) and then keys(ascending) if they match)

the outcome should be like:

ListMap("t"->5, "b"->3, "a"->2, "z"->2, "c"->1)

What is the most efficient way of doing this.

Any help would be appreciated.

Thanks


Dennis Haupt

unread,
Aug 20, 2013, 10:07:08 AM8/20/13
to Jetinder Rathore, scala...@googlegroups.com
just use any of the existing sort methods and apply a custom comparison function
 
Gesendet: Dienstag, 20. August 2013 um 15:25 Uhr
Von: "Jetinder Rathore" <jetinder.s...@gmail.com>
An: scala...@googlegroups.com
Betreff: [scala-user] Sorting maps in Scala.
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Marko Elezovic

unread,
Aug 20, 2013, 12:09:30 PM8/20/13
to scala...@googlegroups.com
Hey Jetinder,
you probably want to do something like:

    val m = Map("z" -> 2, "c" -> 1, "b" -> 3, "a" -> 2, "t" -> 5)
   
    import scala.collection.immutable.ListMap
    ListMap.empty ++ m.toIndexedSeq.sortBy(kv => (-kv._2, kv._1))


A bit of a warning, though. Keep in mind that the ListMap interface leaves something to be desired if you are using big sets of data.
Its complexity is O(n) because it needs to scan through all of its elements until it actually does find something it needs.

I would wholeheartedly recommend using the ever so wonderful LinkedHashMap instead - if you need a fast insertion / lookup:

    import scala.collection.mutable.LinkedHashMap
    LinkedHashMap.empty ++ m.toIndexedSeq.sortBy(kv => (-kv._2, kv._1))

If you are annoyed by the fact that it's a mutable collection, you can use my immutable insertion-order-retaining collections (IORC) at:
https://github.com/melezov/pgscala/blob/2.10.x/iorc/src/main/scala/org/pgscala/iorc/

    libraryDependencies += "org.pgscala" %% "pgscala-iorc" % "0.1.7-1"

Regards,
Marko

Jetinder Rathore

unread,
Aug 20, 2013, 12:42:39 PM8/20/13
to scala...@googlegroups.com
Hi Marko,

Thanks for wonderful reply.

The only reason i don't want to use LinkedHashMap is the fact that its mutable and in my case my collection is going to be relatively very small(not more than 10) so ListMap will do.

But i will definitely try to use IORC if it fits better in my case.

Thanks,
Jetinder 
Reply all
Reply to author
Forward
0 new messages