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!
You can simply create a new HashMap from the existing Map using the copy constructor. HashMap<String, Object> = new HashMap<>(immutableMap);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With