Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Scala collection Seq[(Int, Seq[String])] to Java collection List[(int, List[String])]?

Tags:

java

scala

I know that there are two extremely useful objects in scala.collection package, which will help us to achieve this goal:

  • JavaConverters (If I want to be explicit and tell exactly what I want to convert)
  • JavaConversions (If I don’t want co control conversions and let compiler make implicit work for me)

but I have some troubles to apply them in my case because my data structure is a little bit more complex than the other ones that I saw in many examples.

I'm in scala code and I want that my scala function return a Java collection. So I wanto to convert Scala Seq[(Int, Seq[String])] to Java collection List[(int, List[String])].

How can I do this?

like image 304
Fobi Avatar asked Jun 04 '26 15:06

Fobi


1 Answers

Use map to at first map Seq[(Int, Seq[String])] to Seq[(Int, List[String])] and then use again the same function to main collection

import scala.collection.JavaConversions
val seq : Seq[(Int, Seq[String])] = some code
val seqOfLists = seq.map(s => (s._1, JavaConversions.seqAsJavaList(s._2)))
val listOfLists = JavaConversions.seqAsJavaList(seqOfLists)

Or newer API:

import scala.collection.JavaConverters._
val seq : Seq[(Int, Seq[String])] = some code
val seqOfLists = seq.map(s => (s._1, s._2.asJava))
val listOfLists = seqOfLists.asJava
like image 139
T. Gawęda Avatar answered Jun 06 '26 04:06

T. Gawęda