ps0604
ps0604

Reputation: 1081

Convert java.util.ArrayList to Seq in Scala

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?

Upvotes: 0

Views: 4694

Answers (3)

awadhesh14
awadhesh14

Reputation: 89

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

Upvotes: 0

Patrick Refondini
Patrick Refondini

Reputation: 685

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?

Upvotes: 1

Chitral Verma
Chitral Verma

Reputation: 2853

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.

Upvotes: 4

Related Questions