Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String list into Map[String, List]

Tags:

scala

I'm trying to convert List("a,1" , "b,2" , "c,3" , "a,2" , "b,4") to type scala.collection.immutable.HashMap[String, java.util.List[String]] with values :

a -> 1,2
b -> 2,4
c -> 3

So each key contains a List of its values.

Here is my code so far :

object ConvertList extends Application {

  var details = new scala.collection.immutable.HashMap[String, java.util.List[String]]

  val strList = List("a,1" , "b,2" , "c,3" , "a,2" , "b,4")

  //Get all values
  val getValue : Function1[String, String] = { a => a.split(",")(1) }
  val allValues : List[String] = strList map getValue

  //get unique values
  val uniqueValues = allValues.toSet[String]

  //Somehow map each unique value to a value in the original List....
  println(uniqueValues)

  println(strList.flatten)
  //userDetails += "1" -> List("a","b",


}

How can this conversion be performed ?

like image 816
blue-sky Avatar asked Aug 29 '13 20:08

blue-sky


Video Answer


1 Answers

strList.map(s => (s(0).toString,s(2).toString))
       .groupBy(_._1)
       .mapValues(_.map(_._2))

Output :

Map[String,List[String]] = Map(b -> List(2, 4), a -> List(1, 2), c -> List(3))
like image 81
Marth Avatar answered Nov 04 '22 22:11

Marth