Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 752
Alt Avatar asked Dec 04 '25 18:12

Alt


1 Answers

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))
like image 89
Tyth Avatar answered Dec 06 '25 10:12

Tyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!