3

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?

0

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

12 Comments

@AlexSavitsky Ok I added newer API. I didn't notice deprecation, nice catch
@AlexSavitsky BTW, Thanks for information why you downvoted - that caused that I had possibility to change the question and also learn something. That is very community-friendly way of improvements in answers ;)
Upvoted it back. This is a great example of positive collaboration.
@Fobi note () - it's a normal Java function
@Fobi Full signature is List<Tuple2<Int, List<String>>>
|
3

JavaConversions is deprecated since Scala 2.12.0. Use JavaConverters instead:

import scala.collection.JavaConverters._

val seq: Seq[(Int, Seq[String])] = ???
val javaList = seq.map(x => (x._1, x._2.asJava)).asJava
// java.util.List[(Int, java.util.List[String])]

Comments

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.