codeology
codeology

Reputation: 357

How to sort Scala maps by value in ascending order?

I have a map like so:

var map:Map[String, Double] = Map(
 "1" -> 4.6, 
 "2" -> 2.1, 
 "3" -> 3.4, 
 "4" -> 0.3
)

I would like to sort it by values in the ascending order so as to get the following output after printing each key value pair in the map:

(4,0.3)
(2,2.1)
(3,3.4)
(1,4.6)

How can I do this? Obviously the sorted method doesn't exist so I'd have to convert the Map to another data type and work from there.

Upvotes: 2

Views: 2296

Answers (1)

Leo C
Leo C

Reputation: 22439

Just transform the Map to a List and apply sortBy with an orderer for Double (for Scala 2.13+), like below:

implicit val orderer = Ordering.Double.TotalOrdering

myMap.toList.sortBy(_._2)
// res1: List[(String, Double)] = List((4,0.3), (2,2.1), (3,3.4), (1,4.6))

Upvotes: 4

Related Questions