2

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!

Community
  • 1
  • 1
Alt
  • 2,597
  • 5
  • 26
  • 36

3 Answers3

7
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))
Tyth
  • 1,774
  • 1
  • 11
  • 17
6

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

elm
  • 20,117
  • 14
  • 67
  • 113
3

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  
Keith Pinson
  • 1,725
  • 1
  • 14
  • 17