0

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

1
  • just use initialType.groupBy(_._1._1) Commented Aug 12, 2015 at 14:31

1 Answer 1

1
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))))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, modified slightly to sort : initialType.groupBy(_._1._1).toArray.map(m => (m._1 , m._2.sortBy(s => s._2)))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.