【问题标题】:Scala function toMap to SortedMap or TreeMap?Scala函数toMap到SortedMap或TreeMap?
【发布时间】:2014-10-15 07:14:34
【问题描述】:

是否可以在点“A”处返回带有 toMap 函数的 SortedMap 或 TreeMap?还是需要遵守此任务的“B”点?
答:

val list = List(5, 4, 3).map(i => i -> i ).toMap
println(list)
Map(5 -> 5, 4 -> 4, 3 -> 3)

乙:

println(SortedMap[Int, Int]() ++ list)
Map(3 -> 3, 4 -> 4, 5 -> 5)

【问题讨论】:

    标签: scala


    【解决方案1】:

    一般来说,您可以使用to[Coll] 方法。由于类型参数的数量,它在这里失败了:

    import scala.collection.immutable.SortedMap
    
    // error: SortedMap takes two type parameters, expected: one
    val list = List(5, 4, 3).map(i => i -> i ).to[SortedMap]
    

    但是您可以注释返回类型并使用breakOut 导入,它为任意集合类型提供必要的构建器工厂:

    import scala.collection.breakOut
    val list: SortedMap[Int, Int] = List(5, 4, 3).map(i => i -> i)(breakOut)
    

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      相关资源
      最近更新 更多