如何转换Java地图以在Scala中使用? [英] How can I convert a Java map of maps for use in Scala?

查看:67
本文介绍了如何转换Java地图以在Scala中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个Scala程序,该程序从Java库中调用一个函数,处理结果,并输出CSV.

I working on a Scala program that calls a function from a Java library, processes the results, and spits out a CSV.

有问题的Java函数如下所示:

The Java function in question looks like this:

    Map<String, Map<String, AtomicLong>> getData();

Scala:

    import scala.collection.JavaConversions._
    def analysisAndCsvStuff(data: Map[String, Map[String, AtomicLong]]): Unit { ... }

错误:

    type mismatch;
    found:java.util.Map[java...String,java...Map[java...String,java...AtomicLong]]
    required: scala...Map[String,scala...Map[String,java...AtomicLong]]

(路径名破坏了格式.)

(The path names were ruining the formatting.)

我猜测JavaConversions可以成功转换外部java ... Map,但不能成功转换内部java ... Map.我看到了这个问题但我不确定如何编写显式隐式转换".

I'm guessing that the JavaConversions can successfully convert the outer java...Map but not the inner java...Map. I saw this question but I am unsure of how to go about writing an "explicit implicit conversion".

推荐答案

编辑:请注意,您将获得可变的映射.如果您要使用不可变的内容,则始终可以使用.asScala.toMap.

Note that you will get mutable maps out of this. You can always use .asScala.toMap if you want immutable ones.

JavaConversions 的原始答案:

The original answer with JavaConversions:

简短的答案是:调用外部地图上的.mapValues来转换内部地图:

The short answer is: call .mapValues on the outer map to convert the inner map:

import scala.collection.JavaConversions._
val myScalaMap = myJavaMap.mapValues(_.toMap)

.mapValues强制将转换或外部映射转换为scala Map,而.toMap强制将内部映射转换为scala( immutable )映射.不变部分不是严格必需的,但是无论如何...

.mapValues forces the conversion or the outer map to a scala Map and .toMap forces the conversion of the inner map to a scala (immutable) map. The immutable part isn't strictly necessary, but anyways...

这与此答案非常相似.简短示例:

This is very similar to this anwser. Short example:

scala> val a: java.util.Map[String, java.util.Map[String, String]] = new java.util.HashMap[String, java.util.Map[String, String]]
a: java.util.Map[String,java.util.Map[String,String]] = {}


scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> val myScalaMap = a.mapValues(_.toMap)
myScalaMap: scala.collection.Map[String,scala.collection.immutable.Map[String,String]] = Map()

这篇关于如何转换Java地图以在Scala中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆