Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort map by value

Tags:

scala

I have List[(String,String)] and I need to sort them by the 2nd value and return a map

I have done the following:

val newMap = list.sortBy(_._2).foldLeft(Map.empty[String, String]) {
      (map, key) ⇒ map + (key._1 → key._2)
    }

list is a List[(String,String)]

However the returnning map isn't sorted!!

like image 619
Echo Avatar asked Apr 01 '12 16:04

Echo


1 Answers

Default Map implementations are hash-based and they do not preserve order. Instead use scala.collection.mutable.LinkedHashMap:

val newMap = list.sortBy(_._2).foldLeft(new LinkedHashMap[String, String]) {
    (map, key) => map += (key._1 -> key._2)
    map
}

As suggested by @Rex Kerr, scala.collection.immutable.ListMap might be a better choice for target type:

val newMap = list.sortBy(_._2).foldLeft(new ListMap[String, String]) {
    (map, key) => map + (key._1 -> key._2)
}

Or (once again full credits should go to @Rex Kerr):

val newMap = new ListMap() ++ list.sortBy(_._2)

However what do you really want to achieve? Looks like you might be choosing wrong data structure...

like image 59
Tomasz Nurkiewicz Avatar answered Sep 26 '22 14:09

Tomasz Nurkiewicz