Alt
Alt

Reputation: 2755

How can I sort a dictionary by key in Scala?

It is easy to sort a Map by keys or values in Python (this question for example).

I would like to do the same thing in Scala, lets say I have a dictionary like:

val A= Map(0 -> 1.0, 3 -> 5.0,2->7.0)

I would like to get a List of tuples that correspond to the sorted Map by keys:

val A_sorted= List((0,1.0),(2,7.0),(3,5.0))

Thanks!

Upvotes: 2

Views: 998

Answers (3)

elm
elm

Reputation: 20435

It suffices to

A.toList.sorted

In sorting duples, the first coordinate is sorted first; on equality the second coordinate is used.

To note that in Scala labels with first letter in uppercase by convention denote types (or classes).

Upvotes: 6

Keith Pinson
Keith Pinson

Reputation: 1725

One way is to use the :_* syntax to output the contents of a Sequence and then to convert your map to a sortedMap:

val a = Map(0 -> 1.0, 3 -> 5.0,2->7.0)

val sortedA = scala.collection.immutable.SortedMap(a.toList:_*)

You can convert it to a list if needed:

sortedA.toList  

Upvotes: 3

Tyth
Tyth

Reputation: 1824

Map(0 -> 1.0, 3 -> 5.0,2->7.0).toList.sortBy(_._1)

res1: List[(Int, Double)] = List((0,1.0), (2,7.0), (3,5.0))

Upvotes: 7

Related Questions