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 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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With