从Array [((String,String),Double)]转换为Array [(String,Array [((String,String),Double)])]

时间:2015-08-12 14:25:19

标签: scala

这是两个字符串及其数字值之间的比较数组:

  val initialType: Array[((String, String), Double)] = Array((("a", "a"), 0), (("a", "b"), 3), (("a", "c"), 2),
    (("d", "b"), 2), (("d", "c"), 1), (("d", "d"), 0))

转换后的数组包含一个已排序的子数组   单独的字符串“a”和“d”是每个比较的标题标签:

  val convertedType: Array[(String, Array[((String, String), Double)])] = Array(("a", Array((("a", "a"), 0.0), (("a", "c"), 2.0), (("a", "b"), 3.0))),
    ("d", Array((("d", "d"), 0.0), (("d", "c"), 1.0), (("d", "b"), 2.0))))

这是我到目前为止所做的:

object Convert extends App {

  val initialType: Array[((String, String), Double)] = Array((("a", "a"), 0), (("a", "b"), 3), (("a", "c"), 2),
    (("d", "b"), 2), (("d", "c"), 1), (("d", "d"), 0))

  val numberUniqueUsers = initialType.map(m => m._1._1).distinct.size
  val grouped: Iterator[Array[((String, String), Double)]] = initialType.grouped(numberUniqueUsers)

  val sortedGroups : Iterator[Array[((String, String), Double)]] = grouped.map(m => m.sortBy(s => s._2))

  sortedGroups.foreach(g => g.foreach(println))

}

打印哪些:

((a,a),0.0)
((a,b),3.0)
((a,c),2.0)
((d,b),2.0)
((d,d),0.0)
((d,c),1.0)

如何将其转换为Array[(String, Array[((String, String), Double)])]

1 个答案:

答案 0 :(得分:1)

initialType.groupBy(_._1._1).toArray

例如

@ val initialType: Array[((String, String), Double)] = Array((("a", "a"), 0.0), (("a", "b"), 3.0), (("a", "c"), 2.0),
  (("d", "b"), 2.0), (("d", "c"), 1.0), (("d", "d"), 0.0))
initialType: Array[((String, String), Double)] =
  Array((("a", "a"), 0.0), (("a", "b"), 3.0), (("a", "c"), 2.0), (("d", "b"), 2.0), (("d", "c"), 1.0), (("d", "d"), 0.0))

@ initialType.groupBy(_._1._1).toArray
res3: Array[(String, Array[((String, String), Double)])] =
  Array(("d", Array((("d", "b"), 2.0), (("d", "c"), 1.0), (("d", "d"), 0.0))), ("a", Array((("a", "a"), 0.0), (("a", "b"), 3.0), (("a", "c"), 2.0))))