将字符串列表转换为Map [String,List]

blu*_*sky 7 scala

我正在尝试使用值转换List("a,1" , "b,2" , "c,3" , "a,2" , "b,4")为type scala.collection.immutable.HashMap[String, java.util.List[String]]:

a -> 1,2
b -> 2,4
c -> 3
Run Code Online (Sandbox Code Playgroud)

因此每个键包含其值的列表.

到目前为止,这是我的代码:

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",


}
Run Code Online (Sandbox Code Playgroud)

如何进行此转换?

Mar*_*rth 13

strList.map(s => (s(0).toString,s(2).toString))
       .groupBy(_._1)
       .mapValues(_.map(_._2))
Run Code Online (Sandbox Code Playgroud)

输出:

Map[String,List[String]] = Map(b -> List(2, 4), a -> List(1, 2), c -> List(3))
Run Code Online (Sandbox Code Playgroud)

  • 是的,它将每个字符串映射到这对夫妇('第一个字母','第三个字母').(所以"a,1"到("a","1")).你可以(而且这个代码不仅仅是脑筋急转弯)编写一个函数formatString(s)并使用strList.map(formatString).groupBy(...)来更好地处理特殊情况(string.length <3等) ) (2认同)