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?

3
  • 1
    Possible duplicate of Converting a Java collection into a Scala collection Commented Apr 13, 2018 at 2:56
  • Specifically, this answer would seem to be what you're looking for. Commented Apr 13, 2018 at 2: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. Commented Apr 13, 2018 at 2:58

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I had to do val seq = array.map(_.toSeq).toSeq
@peterSc the second .toSeq is a redundant collection conversion, so removed it. seq has a Seq type.Do mark it as accepted if it helped.
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?

Comments

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

3 Comments

JavaConversions is not a member of package collection
seems like it is a member now, I checked on Scala 2.11.12
2.11.12? That's far, far, from "the latest way."

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.