31

I'm calling a Scala method, from Java. And I need to make the conversion from Seq to List.

I can't modified the signature of the Scala method, so I can't used the asJavaCollection method from scala.collection.JavaConversions._

Any ideas of how can I achieve this?

Using Scala 2.9.3

Cacho Santa
  • 6,846
  • 6
  • 41
  • 73

4 Answers4

48

You're on the right track using JavaConversions, but the method you need for this particular conversion is seqAsJavaList:

java.util.List<String> convert(scala.collection.Seq<String> seq) {
    return scala.collection.JavaConversions.seqAsJavaList(seq);
}

Update: JavaConversions is deprecated, but the same function can be found in JavaConverters.

java.util.List<String> convert(scala.collection.Seq<String> seq) {
    return scala.collection.JavaConverters.seqAsJavaList(seq);
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • I'm not able to **import scala.collection.JavaConversions;** in eclipse. its showing Error here – Ashish Ratan Mar 20 '14 at 05:43
  • Not sure if this is new or not but I had to do `seqAsJavaList(seq).asJava` to get the actual `List` – grinch Mar 04 '15 at 19:41
  • Just added an anonymous edit to this point to use the new JavaConverters class (since 2.8.1). Hopefully will be approved. – Decoded Apr 20 '19 at 19:36
  • @Decoded: Thanks for the improvement :) I didn't accept the edit as-is because I wanted the answer to still make sense in the context of the question, but I added an amendment that uses `JavaConverters`. – Chris Martin Apr 20 '19 at 22:09
  • Thanks! Love to be on the cutting edge :D – Decoded Apr 21 '19 at 03:25
8

Since Scala 2.9, you shouldn't use implicits from JavaConversions since they are deprecated and will soon be removed. Instead, to convert Seq into java List use convert package like this (although it doesn't look very nice):

import scala.collection.convert.WrapAsJava$;

public class Test {
    java.util.List<String> convert(scala.collection.Seq<String> seq) {
        return WrapAsJava$.MODULE$.seqAsJavaList(seq);
    }
}
Mark
  • 1,788
  • 1
  • 22
  • 21
4lex1v
  • 21,367
  • 6
  • 52
  • 86
8

Since 2.12 this is the recommended way:

public static <T> java.util.List<T> convert(scala.collection.Seq<T> seq) {
    return scala.collection.JavaConverters.seqAsJavaList(seq);
}

All other methods a @deprecated("use JavaConverters or consider ToJavaImplicits", since="2.12.0")

berezovskyi
  • 3,133
  • 2
  • 25
  • 30
0

(In case you want to do this conversion in Scala code)

You can use JavaConverters to make this really easy.

import collection.JavaConverters._
val s: Seq[String] = ...
val list: java.util.List<String> = s.asJava
rasen58
  • 4,672
  • 8
  • 39
  • 74