java map 转换 scala,如何从java.util.Map转换为Scala Map

A Java API returns a java.util.Map;. I would like to put that into a Map[String,Boolean]

So imagine we have:

var scalaMap : Map[String,Boolean] = Map.empty

val javaMap = new JavaClass().map() // Returns java.util.Map

You can't do Map.empty ++ javaMap, because the ++ method does not know about Java maps. I tried:

scalaMap = Map.empty ++ new collection.jcl.MapWrapper[String,Boolean] {

override def underlying = javaMap

}

and:

scalaMap = Map.empty ++ new collection.jcl.MapWrapper[java.lang.String,java.lang.Boolean] {

override def underlying = javaMap

}

These both fail to compile, because of the generics - java.lang.String is not the same as a scala String.

Is there a good way of doing this, short of copying the map manually?

EDIT: Thanks, all good answers, I learned a lot from all of them. However, I made a mistake by posting a simpler problem here than the one I actually have. So, if you allow me, I'll generalise the question - What the API actually returns is

java.util.Map>

And I need to move this to Map[String, Map[SomeJavaEnum,String]]

It probably does not seem like too much of a complication, but it adds an extra level of type erasure, and the only way I found of moving this to a Scala map was deep-copying it (using some of the techniques you suggested below). Anyone any hints? I kind of solved my problem by defining an implicit conversion for my exact types, so at least the ugliness is hidden in its own trait, but still feels a bit clumsy deep copying the lot.

解决方案

At least with Scala 2.9.2 there's an easier way with the collections conversions: import "import collection.JavaConversions._" and use "toMap".

Example:

// show with Java Map:

scala> import java.util.{Map=>JMap}

scala> val jenv: JMap[String,String] = System.getenv()

jenv: java.util.Map[String,String] = {TERM=xterm, ANT_OPTS=-Xmx512m ...}

scala> jenv.keySet()

res1: java.util.Set[String] = [TERM, ANT_OPTS...]

// Now with Scala Map:

scala> import collection.JavaConversions._

scala> val env: Map[String,String] = System.getenv.toMap //

env: Map[String,String] = Map(ANT_OPTS -> -Xmx512m, TERM -> xterm ...)

// Just to prove it's got Scala functionality:

scala> env.filterKeys(_.indexOf("TERM")>=0)

res6: scala.collection.immutable.Map[String,String] = Map(TERM -> xterm,

TERM_PROGRAM -> iTerm.app, ITERM_PROFILE -> Default)

It works fine with a java.util.map of String to Boolean.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值