在Scala中将Map [Int,Array [(Int,Int)]]转换为Map [Int,Map [Int,Int]]

时间:2018-07-24 18:57:29

标签: arrays scala dictionary type-conversion

我有这样的数据结构:

Map(
  0 -> Array((1,1), (2,1)),
  1 -> Array((2,1), (3,1), (0,1)),
  2 -> Array((4,1), (0,1), (1,1)),
  3 -> Array((1,1)),
  4 -> Array((5,1), (2,1)),
  5 -> Array((4,1))
)

我需要的结果应如下所示:

Map(
  0 -> Map(1 -> 1, 2 -> 1),
  1 -> Map(2 -> 1, 3 -> 1, 0 -> 1),
  2 -> Map(4 -> 1, 0 -> 1, 1 -> 1),
  3 -> Map(1 -> 1),
  4 -> Map(5 -> 1, 2 -> 1),
  5 -> Map(4 -> 1)
)

1 个答案:

答案 0 :(得分:4)

这很简单:yourMap.mapValues(_.toMap)

scala> :paste
// Entering paste mode (ctrl-D to finish)

Map(
  0 -> Array((1,1), (2,1)),
  1 -> Array((2,1), (3,1), (0,1)),
  2 -> Array((4,1), (0,1), (1,1)),
  3 -> Array((1,1)),
  4 -> Array((5,1), (2,1)),
  5 -> Array((4,1))
)

// Exiting paste mode, now interpreting.

res0: scala.collection.immutable.Map[Int,Array[(Int, Int)]] = Map(0 -> Array((1,1), (2,1)), 5 -> Array((4,1)), 1 -> Array((2,1), (3,1), (0,1)), 2 -> Array((4,1), (0,1), (1,1)), 3 -> Array((1,1)), 4 -> Array((5,1), (2,1)))

scala> res0.mapValues(_.toMap)
res1: scala.collection.immutable.Map[Int,scala.collection.immutable.Map[Int,Int]] = Map(0 -> Map(1 -> 1, 2 -> 1), 5 -> Map(4 -> 1), 1 -> Map(2 -> 1, 3 -> 1, 0 -> 1), 2 -> Map(4 -> 1, 0 -> 1, 1 -> 1), 3 -> Map(1 -> 1), 4 -> Map(5 -> 1, 2 -> 1))