I have list of Map.
List(Map(term_id -> 20898477-2374-4d4c-9af0-8ed9c9829c94),
Map(term_id -> 6d949993-1593-4491-beae-eb9bf8abcf27),
Map(term_id -> 1123c413-3ffd-45ed-8215-dd1bccb3a48f))
and want to get all value and check if a term_id already exist in above list of Map.
This can be done with iterating list and checking value of each map. But I want something more efficient and one liner. I am okay with either of Java or Scala approach.
This question may be naive, but I am not getting at how to proceed. I am new to Java/Scala.
Expected Output:
List(20898477-2374-4d4c-9af0-8ed9c9829c94, 6d949993-1593-4491-beae-eb9bf8abcf27,
123c413-3ffd-45ed-8215-dd1bccb3a48f)
I think flatMap is what you want:
val maplist=List(Map("term_id" -> "20898477-2374-4d4c-9af0-8ed9c9829c94"), Map("term_id" -> "6d949993-1593-4491-beae-eb9bf8abcf27"), Map("term_id" -> "1123c413-3ffd-45ed-8215-dd1bccb3a48f"))
maplist.flatMap(_.values)
//res0: List[String] = List(20898477-2374-4d4c-9af0-8ed9c9829c94, 6d949993-1593-4491-beae-eb9bf8abcf27, 1123c413-3ffd-45ed-8215-dd1bccb3a48f)
maplist.flatMap(_.keys)
//res1: List[String] = List(term_id, term_id, term_id)
you can use below code to get list of values
val maplist=List(Map("term_id" -> "20898477-2374-4d4c-9af0-8ed9c9829c94"), Map("term_id" -> "6d949993-1593-4491-beae-eb9bf8abcf27"), Map("term_id" -> "1123c413-3ffd-45ed-8215-dd1bccb3a48f"))
maplist.map(x=>x.get("term_id")
Output:
List[Option[String]] = List(Some(20898477-2374-4d4c-9af0-8ed9c9829c94), Some(6d949993-1593-4491-beae-eb9bf8abcf27), Some(1123c413-3ffd-45ed-8215-dd1bccb3a48f))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With