如何在Java中将java.util.Map转换为scala.collection.immutable.Map? [英] How do I convert a java.util.Map to scala.collection.immutable.Map in Java?

查看:1519
本文介绍了如何在Java中将java.util.Map转换为scala.collection.immutable.Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很多人都试图这样做,并询问这个问题,但问题总是以scala代码的形式回答。我需要调用一个期望scala.collection.immutable.Map的API,但我有一个java.util.Map,如何在我的java代码中从后者干净地转换为前者?编译器不同意这是一种隐含转换的观点,因为当我尝试时它是barfs!



谢谢!

toMap 因为它需要一个隐式参数,Java编译器当然不会提供。具有该隐式参数的完整解决方案如下所示:

  import scala.collection.JavaConverters $; 
import scala.collection.immutable.Map;

公共课无论{
public< K,V>映射< K,V> convert(java.util.Map< K,V> m){
返回JavaConverters $ .MODULE $ .mapAsScalaMapConverter(m).asScala()。toMap(
scala.Predef $ .MODULE $。< ; scala.Tuple2< K,V>> conforms()
);
}
}

使用<$>用Java编写转换更简洁c $ c> JavaConversions ,但在Scala方面,基本上每个人都希望尽快废弃这些废话,所以即使在这里也要避免使用它。


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!

解决方案

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.

这篇关于如何在Java中将java.util.Map转换为scala.collection.immutable.Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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