The Artima Developer Community
Sponsored Link

Scala Buzz
Sorting a map by it's value

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Zemian Deng

Posts: 49
Nickname: zdeng
Registered: Jan, 2008

Zemian Deng is the creator of SweetScala web framework
Sorting a map by it's value Posted: Nov 17, 2008 11:30 PM
Reply to this message Reply

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
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Zemian Deng
Latest Posts From thebugslayer

Advertisement

Question

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>

Read: Sorting a map by it's value

Topic: Scala Plugin for Coming NetBeans 6.5 Official Release Previous Topic   Next Topic Topic: Scala: breaking/chunking a list into list of list

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use