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!!
Default
Mapimplementations are hash-based and they do not preserve order. Instead usescala.collection.mutable.LinkedHashMap:As suggested by @Rex Kerr,
scala.collection.immutable.ListMapmight be a better choice for target type:Or (once again full credits should go to @Rex Kerr):
However what do you really want to achieve? Looks like you might be choosing wrong data structure…