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]
coolk
  • 353
  • 2
  • 7
  • 1
    Possible duplicate of [Scala - List\[MyObject\] -> Map\[Long, List\[Long\]\]](https://stackoverflow.com/questions/51212195/scala-listmyobject-maplong-listlong) – Andrey Tyukin Jul 06 '18 at 17:19

1 Answers1

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))
Leo C
  • 22,006
  • 3
  • 26
  • 39