简体   繁体   中英

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] . 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 .

If you just want to get all the values for the key "text" in a sequence, use:

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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