将列表转换为Scala中的映射

时间:2017-04-03 11:53:22

标签: scala

我正在尝试将列表转换为地图并获得下面给出的错误,任何帮助将不胜感激。

我的输入就像这样

list=(ageis=21,nameis="xyz",profession="Tester",city="cuba")

我想要这样的输出

Map(ageis->21,nameis->"xyz",profession->"Tester",city->"cuba")

3 个答案:

答案 0 :(得分:3)

例如,如果输入的是:

val list = List("age=21", "name=xyz", "profession=Tester", "city=cuba")

我可以更容易地想到拥有地图:

val myMap = myList.map(text => text.split("=")).map(a => (a(0) -> a(1))).toMap

答案 1 :(得分:0)

如果您的输入是字符串

val input = """list=(ageis=21,nameis="xyz",profession="Tester",city="cuba")"""

然后你可以做

val myMap =
  input
    .stripPrefix("list=(")
    .stripSuffix(")")
    .split(",")
    .map { entry =>
      val Array(key, value) = entry.split("=")
     (key, value.stripPrefix("\"").stripSuffix("\""))
    }.toMap

结果

答案 2 :(得分:0)

为您写了一个小型的“Type Safe”版本,以便将来证明您收到的数据。

如果字符串字段中有任何数据不包含分隔符或分隔符,则它不会包含在生成的映射中。

然后您可以使用.get():Option [String]来检索结果。 (如果结果在地图内)

val list: List[String] = List("ageis=21", "nameis=xyz", "profession=Tester", "city=cuba")
list.splitToMap()


trait CustomToMapTrait {
  def splitToMap (delimiter: String = "="): Map[String, String]
}


/**
 * Some Type safety for implemented for the parsing. If there is no delimiter available or the text is incorrect it will not be included in the map.
 * This saves you from improper data going through your system.
 *
 * Added some functionality so that you can add your own custom delimiter for if it should change
 */

implicit def splitToMap (list: List[String]): CustomToMapTrait = new CustomToMapTrait {
  private def toOptionMap (values: List[String]): Option[Map[String, String]] = {
    if (values.length == 2) values.headOption.fold[Option[Map[String, String]]](None)(l => values.lift(1).fold[Option[Map[String, String]]](None)(r => Some(Map(l -> r))))
    else None
  }
  override def splitToMap (delimiter: String = "="): Map[String, String] = {
    list.foldLeft[Map[String, String]](Map())((acc, value) => toOptionMap(value.split(delimiter).toList).fold(acc)(_ ++ acc))
  }
}