Shashank V C
Shashank V C

Reputation: 153

How to convert Java Map of Lists to Scala Map of Lists

I have a Java Map of lists,

Map<String, List<String>> stringToListOfStrings = new HashMap<String, List<String>>();
        stringToListOfStrings.put("key1", Arrays.asList("k1v1", "k1v2"));
        stringToListOfStrings.put("key2", Arrays.asList("k2v1", "k2v2"));
        stringToListOfStrings.put("key3", Arrays.asList("k3v1", "k3v2"));

I want to convert this to Scala Map of lists

Map[String,List[String]]

Would like to know the conversion on both in Java and Scala.

I have tried this but didn't get the expected output

and on Scala side,

def convertJavaToScala(stringString: java.util.HashMap[String, java.util.List[String]]) {
    val scalaMap = stringString.asScala
    scalaMap.get("key1")
    scalaMap.get("key1").foreach(println)
  }

but the result was a comma separated string of values.

Upvotes: 2

Views: 461

Answers (2)

Tim
Tim

Reputation: 27356

This is an efficient way of doing the conversion:

def convertJavaToScala(ss: java.util.HashMap[String, java.util.List[String]]): Map[String, List[String]] =
  ss.asScala.map{ case (k, v) => k -> v.asScala.toList }(collection.breakOut)

Using map rather than mapValues avoids repeatedly evaluating the conversion code when elements of the Map are accessed. Using collection.breakOut means that an immutable.Map will be created directly from the map call so there is no need to convert to immutable.Map before the map call.

Upvotes: 2

Valy Dia
Valy Dia

Reputation: 2851

Here is the way to do it:

import scala.collection.JavaConverters._

  def convertJavaToScala(stringString: java.util.HashMap[String, java.util.List[String]]): Map[String,List[String]] = {
    val scalaMap: Map[String, java.util.List[String]] = stringString.asScala.toMap
    scalaMap.mapValues(_.asScala.toList)
  }

And when you run:

import java.util.Arrays

  val stringToListOfStrings = new java.util.HashMap[String, java.util.List[String]]()
  stringToListOfStrings.put("key1", Arrays.asList("k1v1", "k1v2"))
  stringToListOfStrings.put("key2", Arrays.asList("k2v1", "k2v2"))
  stringToListOfStrings.put("key3", Arrays.asList("k3v1", "k3v2"))

convertJavaToScala(stringToListOfStrings)
// Displays
// Map(key1 -> List(k1v1, k1v2), key2 -> List(k2v1, k2v2), key3 -> List(k3v1, k3v2))

Basically, you have to add .toMap / .toList after .asScala because Map and List are immutable in Scala, unlike Java.

Upvotes: 4

Related Questions