Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala – group list by key and map values

I’m trying to do sometihng in Scala,

    var  tupleList = new ListBuffer[(String,List[String])]
    val num1 = List("1","2")
    val num2= List("3","4")
    val num3= List("5","6")
    tupleList+=(("Joe",num1))
    tupleList+=(("Ben",num2))
    tupleList+=(("Joe",num3))

**I want to union between both of the lists with name ‘Joe’, and create one list of numbers: 1,2,5,6 .
So I thought to use groupByKey, but how to explode the values?
mapValues?
How Can I use reduceLeft in this case?

I tried something like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val try3 = vre.groupMapReduce(_._1)(_._2)(_ :: _)

Thanks!

>Solution :

Principle problem was in using :: instead of :::.

With immutable collections your example will look like this:

val input =
  ("Joe" -> List("1","2")) ::
  ("Ben" -> List("3","4")) ::
  ("Joe" -> List("5","6")) ::
  Nil

val result = input.groupMapReduce(_._1)(_._2)(_ ::: _)

print(result.mkString("{", ", ", "}"))
// Output:
// {Joe -> List(1, 2, 5, 6), Ben -> List(3, 4)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading