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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With