This post originated from an RSS feed registered with Scala Buzz
by Zemian Deng.
Original Post: Sorting a map by it's value
Feed Title: thebugslayer
Feed URL: http://www.jroller.com/thebugslayer/feed/entries/atom?cat=%2FScala+Programming
Feed Description: Notes on Scala and Sweet web framework
If we were given a map of id to name as categories data model, how are we going to generate a html drop down input that's sorted by display names?
//example of given data map
val m = Map(
1111 -> "Music",
1021 -> "Audio",
1001 -> "TV & Video",
5011 -> "Computers",
9011 -> "Software",
1311 -> "Phones & Office",
2011 -> "Cameras & Camcorders",
1911 -> "Games & Toys",
6611 -> "Home & Appliances"
)
Answer
Scala map has toList method that will produce a list of tuple(key, value). We can use that and apply the sort with a higher function to sort by the second tuple value.
println("<select name='category'>")
for((k,v) <- m.toList.sort{ (a, b) => a._2 < b._2 })
println("<option value='" + k + "'>" + v + "</option>")
println("</select>")
//This should produce something like this:
<select name='category'>
<option value='1021'>Audio</option>
<option value='2011'>Cameras & Camcorders</option>
<option value='5011'>Computers</option>
<option value='1911'>Games & Toys</option>
<option value='6611'>Home & Appliances</option>
<option value='1111'>Music</option>
<option value='1311'>Phones & Office</option>
<option value='9011'>Software</option>
<option value='1001'>TV & Video</option>
</select>