blue-sky
blue-sky

Reputation: 53876

Convert from Array[((String, String), Double)] to Array[(String, Array[((String, String), Double)])]

This is an array of comparisons between two string and their numberical value :

  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))

The converted array contains a sorted sub array The lone String "a" and "d" are the header labels for each each comparison :

  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))))

Here is what I have so far :

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))

}

Which prints :

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

How to convert this to Array[(String, Array[((String, String), Double)])] ?

Upvotes: 0

Views: 105

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108159

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

example

@ 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))))

Upvotes: 1

Related Questions