元组scala的不可变迭代器映射

时间:2018-06-06 07:34:26

标签: scala dictionary iterator tuples immutability

我在scala中有一个元组映射,我希望从中获取所选的键,值对。

我试过

val m1 = {"a":{"0":"R","1":null,"2":null,"3":12.25.0,"4":null}
         ,"b":{"0":"R","1":null,"2":null,"3":34.75,"4":null}
         ,"c":{"0":"R","1":null,"2":null,"3":56.25,"4":null}
         ,"d":{"0":"R","1":null,"2":null,"3":45.65,"4":null}
         }

然后尝试迭代。但我无法处理这种复杂的表达。

由于我只需要a和b,结果将是

a-> 12.25

d-> 45.65

如何在scala中迭代它?

1 个答案:

答案 0 :(得分:0)

您的数据的Scala等价物如下所示:

val m1: List[(String, List[(String, Any)])] =
  List("a" -> List("0" -> "R", "1" -> null, "2" -> null, "3" -> 12.25, "4" -> null),
       "b" -> List("0" -> "R", "1" -> null, "2" -> null, "3" -> 34.75, "4" -> null),
       "c" -> List("0" -> "R", "1" -> null, "2" -> null, "3" -> 56.25, "4" -> null),
       "d" -> List("0" -> "R", "1" -> null, "2" -> null, "3" -> 45.65, "4" -> null))

获得此格式的数据后,您可以提取所需的数据:

val keys = List("a", "d")
val field = 3

m1.collect{ case (k, v) if keys.contains(k) => (k, v(field)._2) }

如果数据的顺序无关紧要,那么您可以使用Map而不是List,代码会更加清晰:

val field = "3"

m1.collect{ case (k, v) if keys.contains(k) => (k, v(field)) }

这也可以让您删除null值并避免使用Any