0

I have the following structure in Scala:

import java.util.ArrayList
val array = new ArrayList[ArrayList[String]]

// ... add values to array

Now, I need to convert it to Seq[Seq[String]], how can this be achieved?

ps0604
  • 1,227
  • 23
  • 133
  • 330
  • 1
    Possible duplicate of [Converting a Java collection into a Scala collection](https://stackoverflow.com/questions/674713/converting-a-java-collection-into-a-scala-collection) – Silvio Mayolo Apr 13 '18 at 02:56
  • Specifically, [this answer](https://stackoverflow.com/a/3969631/2288659) would seem to be what you're looking for. – Silvio Mayolo Apr 13 '18 at 02:56
  • Thanks, but in that answer the list has one dimension, and in my question it has two. Also, it's from 2010, probably changed by now. – ps0604 Apr 13 '18 at 02:58

3 Answers3

4

You can do the following,

import scala.collection.JavaConversions._
val array = new ArrayList[ArrayList[String]]
val seq: Seq[Seq[String]] = array.map(_.toSeq)
...

Let me know if this helps, Cheers.

Chitral Verma
  • 2,695
  • 1
  • 17
  • 29
1

A second solution using explicit conversions:

import scala.collection.JavaConverters._
import java.util.ArrayList

val array = new ArrayList[ArrayList[String]]

// Mutable, default conversion for java.util.ArrayList
val mutableSeq : Seq[Seq[String]] = array.asScala.map( _.asScala)

// Immutable, using toList on mutable conversion result
val immutableSeq : Seq[Seq[String]] = array.asScala.toList.map( _.asScala.toList)

To clarify the difference between Java JavaConverters and JavaConversions please read:

What is the difference between JavaConverters and JavaConversions in Scala?

0

The scala.collection.JavaConverters._ is depricated. The latest ways is:

import scala.collection.JavaConversions._

val a = asScalaBuffer(array)

Now you can convert a to any of the collections

to        toBuffer       toIterable   toList   toParArray   toSet      toString        toVector
toArray   toIndexedSeq   toIterator   toMap    toSeq        toStream   toTraversable

like this

val b = a.toSeq

Here is a complete tutorial

awadhesh14
  • 89
  • 7