如何将scala.List转换为java.util.List? [英] How to convert a scala.List to a java.util.List?

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

问题描述

如何将Scala的 scala.List 转换为Java的 java.util.List

How to convert Scala's scala.List into Java's java.util.List?

推荐答案

Scala List和Java List是两种不同的野兽,因为前者是不可变的而后者是可变的。因此,要从一个到另一个,首先必须将Scala列表转换为可变集合。

Scala List and Java List are two different beasts, because the former is immutable and the latter is mutable. So, to get from one to another, you first have to convert the Scala List into a mutable collection.

在Scala 2.7上:

On Scala 2.7:

import scala.collection.jcl.Conversions.unconvertList
import scala.collection.jcl.ArrayList
unconvertList(new ArrayList ++ List(1,2,3))

从Scala 2.8开始:

From Scala 2.8 onwards:

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
asList(ListBuffer(List(1,2,3): _*))
val x: java.util.List[Int] = ListBuffer(List(1,2,3): _*)

但是,如果预期的类型是Java 列表,则该示例中的 asList 不是必需的,因为转换是隐含的,如最后一行所示。

However, asList in that example is not necessary if the type expected is a Java List, as the conversion is implicit, as demonstrated by the last line.

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

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