Question

I am using MVC architecture in Play Framework in which the view part is a mix of scala and html. Now, I need to sort a Map coming from the controller layer in my view. As scala has no memory its being really hard to create a sort function to sort my map by timestamp. Can anybody please help i'm really not able to solve this one as i am new to scala.

This is my First Question. Any help would be Appreciated.

Was it helpful?

Solution

Assuming the timestamps are the keys of the map (i.e. it's a Map[Long,B]):

myMap.toSeq.sortBy(_._1) // yields a Seq[Tuple2[Long,B]]

That is, you're converting the map to a Seq first, so that element ordering will be preserved (maps are normally HashMaps, with an unpredictable ordering), then sorting that sequence by the first element of the key-value tuple.

If the timestamps are the values, replace the _._1 with _._2.

Note that if you convert the intermediate Seq back to a Map (e.g. with .toMap), you'll be back in HashMap land again, and your sort will be gone.

So, this might be more like what you want:

scala.collection.immutable.SortedMap(myMap.toSeq: _*) // yields a SortedMap[Long, B]

Here, we convert myMap to a Seq just so that it can be passed to the varargs factory method of SortedMap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top