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

非 Y 不嫁゛ 提交于 2019-12-03 16:38:21

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

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.

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