Home > Blockchain >  Scala - group list by key and map values
Scala - group list by key and map values

Time:12-28

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:

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

Thanks!

CodePudding user response:

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)}
  • Related