简体   繁体   English

Map的Scala访问顺序

[英]Scala access sequence of Maps

I have a IndexedSeq[Map[String, String]] and I would like to extract value where key is "text" and I would like to put it in a val text:IndexedSeq[String] . 我有一个IndexedSeq[Map[String, String]] ,我想提取键为“ text”的值,并将其放在val text:IndexedSeq[String] I have written the following piece but it doesn't work: 我写了以下文章,但没有用:

val text:IndexedSeq[String] = _
for(j <- 0 to indSeq.length-1){
  text(j) = indSeq(j).get("text")
}

You are probably seeing a compiler error because indSeq(j).get("text") returns an Option[String] , not a String . 您可能会看到编译器错误,因为indSeq(j).get("text")返回Option[String]而不是String

If you just want to get all the values for the key "text" in a sequence, use: 如果只想获取序列中键"text"所有值,请使用:

val text = indSeq flatMap (_ get "text")

If it's important that the indices of both sequences line up, then you will want to substitute a default value in case the key "text" is not present: 如果两个序列的索引必须"text"很重要,那么您将要替换默认值,以防键"text"不存在:

val text = indSeq map (_.getOrElse("text", "default"))

Since you were trying to use a for-comprehension originally, you might also be interested in doing it this way: 由于您最初尝试使用理解功能,因此您可能也对这种方式感兴趣:

val text = (for { m <- indSeq } yield m get "text") flatten

EDIT 编辑

or if you want a default value you could do: 或者,如果您想使用默认值,则可以执行以下操作:

val text = for { m <- indSeq } yield m getOrElse("text", "default")

I think the best approach is with a for-comprehension with a guard to get rid of the maps that don't have the "text" element: 我认为最好的方法是对警卫的理解,以摆脱没有"text"元素的地图:

val result = for {
  i <- 0 until indexSeq.length
  map = indexSeq(i)
  if map isDefinedAt ("text")
} yield { (i, map("text")) }

val seq = result.toIndexedSeq

That way you keep the original indexes with the map. 这样,您可以将原始索引与地图保持在一起。 It also avoids holding any var value, which is always a perk 它还避免保存任何var值,该值始终是特权

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM