【问题标题】:List of Lists to HashMap[Index of List] -> List - Scala到 HashMap 的列表列表 [列表索引] -> 列表 - Scala
【发布时间】:2016-10-07 21:24:02
【问题描述】:

我在 Scala 中有一个列表列表,看起来像这样:List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10),我想转换 它进入HashMap[Int, List[Int]],其中第一个 Int 是每个列表的索引,List[Int] 是列表本身。最后 HashMap 应该 看起来像

 HashMap[Int, List[Int]](
      0 -> List(1, 5, 6, 10),
      1 -> List(1, 6),
      2 -> List (1, 3, 10),)

这是我的方法,有一个列表 0 到列表的长度,然后用这个嵌套列表压缩它,然后以某种方式 将其转换为 HashMap。但我正在寻找更惯用或更简洁的东西。有什么想法吗?

【问题讨论】:

    标签: list scala hashmap


    【解决方案1】:

    zipWithIndex 和 map 应该这样做:

    scala> val a = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))
    a: List[List[Int]] = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))
    
    scala> a.zipWithIndex.map(_.swap).toMap
    res0: scala.collection.immutable.Map[Int,List[Int]] = 
    Map(
        0 -> List(1, 5, 6, 10),
        1 -> List(1, 6), 
        2 -> List(1, 3, 10)
    )
    

    编辑:

    如果你绝对需要HashMap,事情就有点麻烦了:

    scala> val a = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))
    a: List[List[Int]] = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))
    
    scala> val b = a.zipWithIndex.map(_.swap)
    b: List[(Int, List[Int])] = List((0,List(1, 5, 6, 10)), (1,List(1, 6)), (2,List(1, 3, 10)))
    
    scala> val hM = collection.immutable.HashMap[Int, List[Int]](b: _*)
    hM: scala.collection.immutable.HashMap[Int,List[Int]] = 
    Map(
        0 -> List(1, 5, 6, 10),
        1 -> List(1, 6),
        2 -> List(1, 3, 10)
    )
    

    【讨论】:

    • 使用_.swap 而不是x => (x._2, x._1)
    • 已添加,我必须记住!
    • 非常好。有什么方法可以将其转换为 HashMap 而不是 Map。我的函数抱怨预期的 HashMap[Int, List[Int]],实际:Map[Int, List[Int]]。
    • @TeodoricoLevoff 查看我对HashMap 转换的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多