在scala中映射多个数组

时间:2016-05-15 11:08:16

标签: scala

我在Scala中有两个数字相同的数组

val v = myGraph.vertices.collect.map(_._1)

给出:

Array[org.apache.spark.graphx.VertexId] = Array(-7023794695707475841, -44591218498176864, 757355101589630892, 21619280952332745)

和另一个

val w = myGraph.vertices.collect.map(_._2._2)

给出:

Array[String] = Array(2, 3, 1, 2)

我想用

创建一个字符串
val z =  v.map("{id:" + _ + "," + "group:" + "1" + "}").mkString(",")

给出:

String = {id:-7023794695707475841,group:1},{id:-44591218498176864,group:1},{id:757355101589630892,group:1},{id:21619280952332745,group:1}

但是现在不是硬编码的" 1",而是想要映射w数组中的数字来给出:

String = {id:-7023794695707475841,group:2},{id:-44591218498176864,group:3},{id:757355101589630892,group:1},{id:21619280952332745,group:2}

我该怎么做?

1 个答案:

答案 0 :(得分:2)

Scala集合中有一个名为zip的方法,它可以按照您需要的方式将两个集合配对。

val v = Array(-37581, -44864, 757102, 21625)
val w = Array(2, 3, 1, 2)

val z = v.zip(w).map { 
  case (v, w) => "{id:" + v + "," + "group:" + w + "}" 
}.mkString(",")

z变为:

{id:-37581,group:2},{id:-44864,group:3},{id:757102,group:1},{id:21625,group:2}