0

I have a list of java HashMaps like below

List[java.util.Map[String,String]] = List({id=1000, sId=1}, {id=2000, sId=1}, {id=3000, sId=2}, {id=3000, sId=1})

How can I convert this to a Map of String, List[String]? e.g.

1000 -> [1]
2000 -> [1]
3000 -> [2,1]
1

1 Answer 1

2

You can use JavaConversions to allow converting java.util.Map to scala.collection.immutable.Map via toMap. As for transforming from List of Map[K, V] to Map[K, List[V]], here's one approach using groupBy-mapValues:

val l: List[java.util.Map[String,String]] = List(
  new java.util.HashMap[String, String] { put("id", "1000"); put("sId", "1") },
  new java.util.HashMap[String, String] { put("id", "2000"); put("sId", "1") },
  new java.util.HashMap[String, String] { put("id", "3000"); put("sId", "2") },
  new java.util.HashMap[String, String] { put("id", "3000"); put("sId", "1") }
)
// l: List[java.util.Map[String,String]] =
//   List({id=1000, sId=1}, {id=2000, sId=1}, {id=3000, sId=2}, {id=3000, sId=1})

import scala.collection.JavaConversions._

l.map(_.toMap.toList.map(_._2)).
  groupBy(_(0)).
  mapValues(_.map(_(1)))
// res1: scala.collection.immutable.Map[String,List[String]] =
//   Map(3000 -> List(2, 1), 1000 -> List(1), 2000 -> List(1))
Sign up to request clarification or add additional context in comments.

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.