在Scala中通过数组数组中的键减少

时间:2017-10-16 19:57:38

标签: scala

我在Scala中创建了一个数组

val L = Array((1,Array(one, two, one)), (2,Array(one, three, three)))

我想得到这个结果:

  Array((1,(one,2), (two,1)), (2,(one,1),(three,2)))

我做了

val LL = L.map({case (s, contents) => (s, contents.map(s=>(s,1)))})

得到了

LL = Array((1,Array((one,1), (two,1), (one,1))), (2,Array((one,1), (three,1), (three,1))))

我想做一个reduceByKey来获得那个结果,但它似乎不起作用。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

尝试:

L.map { case (key, values) => 
  (key, values.groupBy(identity).mapValues(_.size).toArray) 
}

答案 1 :(得分:0)

使用foldLeft迭代数组项的每个第二个值,并计算每个数组中字符串的出现次数。

Scala repl

scala> val arr: Array[(Int, Array[String])] = Array((1, Array("one", "one", "two")))
arr: Array[(Int, Array[String])] = Array((1,Array(one, one, two)))

scala> arr.map { case (k, v) => k -> (v.foldLeft(Map.empty[String, Int])((r, c) => r.get(c).map(x => r.updated(c, x + 1)).getOrElse(r.updated(c, 1))).toArray) }
res16: Array[(Int, Array[(String, Int)])] = Array((1,Array((one,2), (two,1))))