简体   繁体   中英

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

如何将java.util.Map [String,Object]转换为scala.collection.immutable.Map [String,Any],以便将原始映射中的所有值(整数,布尔值等)转换为正确的值在Scala工作得很好。

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)

The JavaConversions package of Scala2.8 deals only with mutable collections.

The scalaj-collection library might help here.

java.util.Map[A, B]       #asScala: scala.collection.Map[A, B]
                          #asScalaMutable: scala.collection.mutable.Map[A, B]
                          #foreach(((A, B)) => Unit): Unit

In order to convert convert java.util.Map[String, Object] to scala.collection.immutable.Map[String,Object] , you need to simple import below statement in Scala Project and clean build.

import collection.JavaConversions._

Refer to below code:

var empMap= Map[String.Object]()
var emp= new Employee(empMap)  // Employee is java  POJO in which,passing scala map  to overloaded constructor for setting default values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM