Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a java.util.Map to scala.collection.immutable.Map in Java?

I find lots of people trying to do this, and asking about this but the question is always answered in terms of scala code. I need to call an API that is expecting a scala.collection.immutable.Map but I have a java.util.Map, how can I cleanly convert from the latter to the former in my java code? The compiler disagrees with the sentiment that it is an implicit conversion as it barfs on that when I try it!

Thank you!

like image 723
NSA Avatar asked Jun 25 '14 18:06

NSA


People also ask

How can we convert mutable map to immutable in Java?

You can simply create a new HashMap from the existing Map using the copy constructor. HashMap<String, Object> = new HashMap<>(immutableMap);

How do I convert a map to a collection?

The collect() method of the Stream class collects the stream of keys in a List. The Collectors. toCollection(ArrayList::new) passed to the collect() method to collect as new ArrayList. One can also use Stream API to convert map keys and values to respective lists.

Is map immutable in Scala?

Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.


1 Answers

Getting an immutable Scala map is a little tricky because the conversions provided by the collections library return all return mutable ones, and you can't just use toMap because it needs an implicit argument that the Java compiler of course won't provide. A complete solution with that implicit argument looks like this:

import scala.collection.JavaConverters$;
import scala.collection.immutable.Map;

public class Whatever {
  public <K, V> Map<K, V> convert(java.util.Map<K, V> m) {
    return JavaConverters$.MODULE$.mapAsScalaMapConverter(m).asScala().toMap(
      scala.Predef$.MODULE$.<scala.Tuple2<K, V>>conforms()
    );
  }
}

Writing conversions in Java is a little cleaner with JavaConversions, but on the Scala side essentially everyone hopes that piece of crap will get deprecated as soon as possible, so I'd avoid it even here.

like image 185
Travis Brown Avatar answered Oct 01 '22 18:10

Travis Brown