Blankman Blankman -4 years ago 147
Scala Question

How to convert a List to a java.util.ArrayList[String]

I'm trying to convert Scala

List
to a Java
ArrayList
.

import collection.JavaConverters._

val list: java.util.ArrayList[String] = List("hello", "world").asJava


It doesn't seem to be working.

How can I do this?

Answer Source

The asJava function returns an object that implements the java.util.List interface. This object is backed by your original list. You can find the documentation for this here (check the seqAsJavaList function):

http://www.scala-lang.org/api/2.12.0/scala/collection/JavaConverters$.html

If you want an instance of java.util.ArrayList, you can create one using the constructor that takes a Collection. Like this:

import java.util.ArrayList
val list = new ArrayList(List("hello", "world").asJava)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download