Convert String list into Map[String, List]
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))
Lists wouldn't be in the same order, but generally it is quite feasible problem:
// for a sake of pithiness
type M = Map[String,List[String]]
def empty: M = Map.empty.withDefaultValue(Nil)
@annotation.tailrec
def group(xs: List[String], m: M = empty): M = xs match {
case Nil => m
case h::tail =>
val Array(k,v) = h.split(",")
val updated = v::m(k)
combine(tail, m + (k -> updated))
}
There are already a good deal of takes, but what about something similar to what Marth proposes:
import scala.collection.JavaConverters._
val strList = List("a,1" , "b,2" , "c,3" , "a,2" , "b,4")
strList.map(_.split(',')).collect {
case Array(key, value) => key -> value
}.groupBy(_._1).mapValues(_.map(_._2).asJava)
This relies heavily on functional programming and ends up with a Map
of type Map[String, java.util.List[String]]
, while not just taking fixed positions in the input string, but splitting at the comma (imagine having numbers over 9, requiring more than one digit).
Also, if there are more than one value from the split, the collect
method filters them away.