Scala:列出[Tuple3]到Map [String,String]

时间:2012-05-28 13:22:15

标签: list scala map type-conversion tuples

我的List[(Int,String,Double)]查询结果需要转换为Map[String,String](在html选择列表中显示)

我的黑客解决方案是:

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

必须有更好的方法来实现同样的目标......

2 个答案:

答案 0 :(得分:9)

这个怎么样?

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

方法collection.breakOut提供了一个CanBuildFrom实例,可确保即使您从List进行映射,也可以重建Map,这要归功于类型注释,并避免创建中间集合。

答案 1 :(得分:8)

更简洁一点:

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

更短的选择:

val prices =
  dao.getPricing.map { p => ( p._1.toString, p._2+" $"+p._3)} toMap
相关问题