3

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)
6
  • iterating through each element is indeed the most efficient way if this same data structure is used Commented Apr 10, 2017 at 5:38
  • @StinePike, is it possible to unpack list of map and find any Map which contains an element as value without iterating? Commented Apr 10, 2017 at 5:42
  • What are in your Maps ? It looks like each one only contains a single entry. Commented Apr 10, 2017 at 5:45
  • Yes, key is same for each Map in List of Map and each Map contain single entry. Commented Apr 10, 2017 at 5:46
  • can you please list final output what you want? Commented Apr 10, 2017 at 5:48

2 Answers 2

8

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.