princess of persia
princess of persia

Reputation: 2232

Scala Print Map in Order

I have a Map[String,String] and I would like to print it in a particular order depending on the keys. For example I would like to print the value of id, name, address. So I would like to match my keys to "id","name", "address" and then print the values at each of these keys. I have the following code but it doesn't work:

articlesmap.keys match{
    case ("id") => println(articlesmap.get("id"))
        case ("name") => println(articlesmap.get("name"))
        case ("address") => println(articlesmap.get("address"))
 }

Upvotes: 1

Views: 1910

Answers (4)

Faiz
Faiz

Reputation: 16265

You could use for:

for { 
  k <- Seq("id", "name", "address") // the keys in the order you want to print them.
  v <- articlesmap.get(k) 
} println (k+ " is " + v)

If you just want to print values, collect will do fine:

Seq("id", "name", "address") collect articlesmap foreach println

collect is better than map id you can't be certain that a key is actually in the map.

Upvotes: 7

Sergey Passichenko
Sergey Passichenko

Reputation: 6930

here is the simplest solution as I know:

scala>  val keys = Seq("id", "name", "address") 
keys: Seq[java.lang.String] = List(id, name, address)

scala>  val articlesmap = Map("id" -> 1, "name" -> "john", "address" -> "some address")
articlesmap: scala.collection.immutable.Map[java.lang.String,Any] = Map(id -> 1, name -> john, address -> some address)

scala>  keys map articlesmap foreach println
1
john
some address

scala>  val keys = Seq("name", "id", "address")
keys: Seq[java.lang.String] = List(name, id, address)

scala>  keys map articlesmap foreach println
john
1
some address

Upvotes: 3

Randall Schulz
Randall Schulz

Reputation: 26486

You could create an OrderedMap or you could sort the keys and process the result of that sort.

Upvotes: 2

nimda
nimda

Reputation: 720

Variable articlesmap.keys is of type Iterable[String], but your case matches are matching on type String. Try this instead:

def mapTest(map: Map[String, String]) {
    map.keys.foreach {
      case ("id") => println(map.get("id"))
      case ("name") => println(map.get("name"))
      case ("address") => println(map.get("address"))
    }
  }                                            

  val mapper = Map("id" -> "123", "name" -> "Bob", "address" -> "123 Fake Street")

  mapTest(mapper)

  // => Some(123)
  //    Some(Bob)
  //    Some(123 Fake Street)

Upvotes: 2

Related Questions