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

青春壹個敷衍的年華 提交于 2019-12-21 05:28:07

问题


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...


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/10785372/scala-listtuple3-to-mapstring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!