使用scala

时间:2016-07-21 05:14:58

标签: scala apache-spark

嗨,我是apache spark和scala的新手。我想转换 Array(('a',1), ('b',(1,1)), ('c',1))Array(('a',1), ('b',2), ('c',1))

请你帮我转换。

1 个答案:

答案 0 :(得分:2)

在问题中没有具体类型的情况下,我假设数组中的值分别是Char和Int元组。以下是我们如何转换为所需的输出:

scala> val a = Array(('a',1), ('b',(1,1)), ('c',1))
a: Array[(Char, Any)] = Array((a,1), (b,(1,1)), (c,1))

scala> a map { case (first, second) => (first, second match { case p: Product =>  Tuple1(p.productIterator.map(_.asInstanceOf[Int]).reduce(_ + _)); case _=> second }) }
res27: Array[(Char, Any)] = Array((a,1), (b,(2,)), (c,1))

基本上我们可以使用productIterator遍历元组中的元素。我们还需要将每个值映射到一个Integer,以便计算总和。

另请查看此问题:Iterate Over a tuple

相关问题