Scala-Groupby Array [(String,Array [String])]由字符串

时间:2018-08-23 20:22:23

标签: scala

我有一个结构,Array[(String,Array[String])] 它包含类似的字符串 例如:

    "A",["b","bc","f","df"]
    "B",["b","df","sef","g"]
    "A",["s","rg","rg"]
    "B",["f","dfv","x"]

我希望将其分组为

    "A",["b","bc","f","df","s","rg","rg"]
    "B",["b","df","sef","g","f","dfv","x"]

有没有办法做到这一点? (是Scala的新手)

1 个答案:

答案 0 :(得分:1)

尝试一下:

input
  .groupBy(_._1)
  .mapValues(_.map(_._2).reduce(_ ++ _).distinct)

示例:

val input = Array(
  ("A", Array("b","bc","f","df")),
  ("B", Array("b","df","sef","g")),
  ("A", Array("s","rg","rg")),
  ("B", Array("f","dfv","x"))
)

val result = input
  .groupBy(_._1)
  .mapValues(_.map(_._2).reduce(_ ++ _).distinct)

for ((c, a) <- result) println(c + " -> " + a.mkString(","))

输出:

A -> b,bc,f,df,s,rg
B -> b,df,sef,g,f,dfv,x