Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all values from List of Map in Scala?

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)
like image 771
Om Prakash Avatar asked Dec 17 '25 21:12

Om Prakash


2 Answers

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)
like image 189
Renkai Avatar answered Dec 20 '25 10:12

Renkai


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))
like image 22
Sandeep Purohit Avatar answered Dec 20 '25 10:12

Sandeep Purohit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!