Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any]

How do I convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any], so that all values in the original map (integers, booleans etc.) are converted to the right value to work well in Scala.

like image 215
IttayD Avatar asked Jun 27 '10 11:06

IttayD


People also ask

How can we convert mutable Map to immutable Scala?

If you just want a mutable HashMap , you can just use x. toMap in 2.8 or collection. immutable. Map(x.

Is Map immutable in Scala?

By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala. collection. mutable.

Can we convert Map to string in Java?

Use Object#toString() . String string = map. toString(); That's after all also what System.

Can we convert object to Map in Java?

In Java, you can use the Jackson library to convert a Java object into a Map easily.


1 Answers

As VonC says, scala.collections.JavaConversion supports mutable collections only, but you don't have to use a separate library. Mutable collections are derived from TraversableOnce which defines a toMap method that returns an immutable Map:

import scala.collection.JavaConversions._  val m = new java.util.HashMap[String, Object]() m.put("Foo", java.lang.Boolean.TRUE) m.put("Bar", java.lang.Integer.valueOf(1))  val m2: Map[String, Any] = m.toMap println(m2) 

This will output

Map(Foo -> true, Bar -> 1) 
like image 99
Michel Krämer Avatar answered Sep 29 '22 12:09

Michel Krämer