Sort list within a map in scala
I have a map like:
val v = Map("01" -> List(34,12,14,23), "11" -> List(22,11,34))
I just can't seem to find a way to sort the list items within the map.
I tried:
v.flatMap(v => v._2.sortBy(list => list._))
but it seems like it doesn't sort the list items.
Does anyone know where I am going wrong?
UPDATE : Actually my list is a list of tuples of type List[(Object1, Object2, Object3, Object4)]
I put in int
for simplicity. (but I think that _.sorted
won't work for my object). So I basically want to sort by one of the columns of these objects. (for example Object1.int
)
source to share
It works:
v.mapValues(_.sorted)
// Map(01 -> List(12, 14, 23, 34), 11 -> List(11, 22, 34))
If your values ββare tuples, try this:
v.mapValues(_.sortBy(_._1))
This approach will also work for classes, just say for example. _.sortBy(_.age)
...
Or if you want one, concatenated list:
v.values.flatten.toSeq.sorted
// List(11, 12, 14, 22, 23, 34, 34)
(for a list of tuples):
v.values.flatten.toSeq.sortBy(_._1)
source to share
Do you mean this?
val v = Map("01" -> List(34,12,14,23), "11" -> List(22,11,34))
//v: scala.collection.immutable.Map[String,List[Int]] = Map(01 -> List(34, 12, 14, 23), 11 -> List(22, 11, 34))
v map { case (k, v) => (k -> v.sorted) }
//res0: scala.collection.immutable.Map[String,List[Int]] = Map(01 -> List(12, 14, 23, 34), 11 -> List(11, 22, 34))
Change or:
v mapValues (_ sorted)
//res1: scala.collection.immutable.Map[String,List[Int]] = Map(01 -> List(12, 14, 23, 34), 11 -> List(11, 22, 34))
Another edit:
If there is an implicit one Ordering
for all types in your tuples, it should work exactly the same:
val v = Map(
"01" -> List((34, "thirty-four"), (12, "twelve"), (14, "fourteen"), (23, "twenty-three")),
"11" -> List((22, "twenty-two"), (11, "eleven"), (34, "thirty-four")))
//v: scala.collection.immutable.Map[String,List[(Int, String)]] =
//Map(
// 01 -> List((34,thirty-four), (12,twelve), (14,fourteen), (23,twenty-three)),
// 11 -> List((22,twenty-two), (11,eleven), (34,thirty-four)))
v mapValues (_ sorted)
//res3: scala.collection.immutable.Map[String,List[(Int, String)]] =
//Map(
// 01 -> List((12,twelve), (14,fourteen), (23,twenty-three), (34,thirty-four)),
// 11 -> List((11,eleven), (22,twenty-two), (34,thirty-four)))
If you only want to sort one member of a tuple (say ... the second in this case):
v mapValues (_ sortBy (_ _2))
//res5: scala.collection.immutable.Map[String,List[(Int, String)]] =
//Map(
// 01 -> List((14,fourteen), (34,thirty-four), (12,twelve), (23,twenty-three)),
// 11 -> List((11,eleven), (34,thirty-four), (22,twenty-two)))