Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: List[Tuple3] to Map[String,String]

I've got a query result of List[(Int,String,Double)] that I need to convert to a Map[String,String] (for display in an html select list)

My hacked solution is:

val prices = (dao.getPricing flatMap {
  case(id, label, fee) =>
    Map(id.toString -> (label+" $"+fee))
  }).toMap

there must be a better way to achieve the same...

like image 240
virtualeyes Avatar asked Dec 03 '22 03:12

virtualeyes


2 Answers

How about this?

val prices: Map[String, String] =
  dao.getPricing.map {
    case (id, label, fee) => (id.toString -> (label + " $" + fee))
  }(collection.breakOut)

The method collection.breakOut provides a CanBuildFrom instance that ensures that even if you're mapping from a List, a Map is reconstructed, thanks to the type annotation, and avoids the creation of an intermediary collection.

like image 80
Jean-Philippe Pellet Avatar answered Dec 05 '22 17:12

Jean-Philippe Pellet


A little more concise:

val prices =
  dao.getPricing.map { case (id, label, fee) => ( id.toString, label+" $"+fee)} toMap

shorter alternative:

val prices =
  dao.getPricing.map { p => ( p._1.toString, p._2+" $"+p._3)} toMap
like image 40
Johnny Everson Avatar answered Dec 05 '22 15:12

Johnny Everson