7

I am using a Java API that requires ArrayList as parameter. Now in Scala, I have a List[String]. How can I convert the List[String] to ArrayList in Scala?

I have tried :

import scala.collection.JavaConverters._
val scalaList = List("a","b","c")
scalaList.asJava

Result is:

java.util.List[String] = [a, b, c]

The above does not work because I want the result to be

java.util.ArrayList[String]

instead of

java.util.List[String] = [a, b, c]

2
  • ArrayList<T> is implementation of List<T> in Java. It makes sense to return List<T>. Commented Jun 13, 2017 at 23:24
  • 1
    List<T> is the interface type that represents any list, and as such it is what most people take as parameter instead of a specific instance. Taking the specific instance without specific comment, and in particular one like ArrayList, should always at least be documented with a good reason. Commented Jun 13, 2017 at 23:41

1 Answer 1

12

It totally makes sense to return java.util.List[T] which is a java interface and can have ArrayList[T] or LinkedList[T] as implementation.

scala> val scalaList = List(1,2,3) 
scalaList: List[Int] = List(1, 2, 3)

scala> import scala.collection.JavaConverters._  
import scala.collection.JavaConverters._

scala> scalaList.asJava
res22: java.util.List[Int] = [1, 2, 3]

In my opinion it needs to be converted to ArrayList[T] or LinkedList[T] whatever you want by yourself.

One way I could think of is

scala> new java.util.ArrayList[Int](scalaList.asJava)
res27: java.util.ArrayList[Int] = [1, 2, 3]

or

scala> new java.util.LinkedList[Int](scalaList.asJava)
res28: java.util.LinkedList[Int] = [1, 2, 3]

Better version of this would be

scala> def toArrayList[T](input: List[T]): java.util.ArrayList[T] = new java.util.ArrayList[T](input.asJava)
toArrayList: [T](input: List[T])java.util.ArrayList[T]

scala> toArrayList(List(1000, 2000, 3000))
res33: java.util.ArrayList[Int] = [1000, 2000, 3000]

And the best version would be, write implicit method

class AsArrayList[T](input: List[T]) {
  def asArrayList : java.util.ArrayList[T] = new java.util.ArrayList[T](input.asJava)
}

implicit def asArrayList[T](input: List[T]) = new AsArrayList[T](input)

List(1000, 2000, 3000).asArrayList
Sign up to request clarification or add additional context in comments.

3 Comments

i tried, val input = List("a","b","c"); myapi(new java.util.ArrayList [String](input.asJava)); But got "value asjava is not a member of List[String]".
did you import import scala.collection.JavaConverters._, thats where asJava method is
scala.collection.JavaConverters has been deprecated since Scala 2.13.0. You should import the extension methods with import scala.jdk.CollectionConverters._.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.