Convert from scala.collection.Seq<String> to java.util.List<String> in Java code
Solution 1
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);
}
Solution 2
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);
}
}
Solution 3
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")
Cacho Santa
#include <stdio.h> int main(int argc, char *argv[]) { printf("90 Hours A Week And Loving It!"); return 0; }
Updated on April 21, 2020Comments
-
Cacho Santa about 4 years
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 fromscala.collection.JavaConversions._
Any ideas of how can I achieve this?
Using Scala 2.9.3
-
Rüdiger Klaehn almost 11 yearsIt might be a good idea for scala to provide a more java-friendly set of frontend methods for these kinds of conversions.
-
Ashish Ratan about 10 yearsI'm not able to import scala.collection.JavaConversions; in eclipse. its showing Error here
-
grinch about 9 yearsNot sure if this is new or not but I had to do
seqAsJavaList(seq).asJava
to get the actualList<E>
-
Tom Wang over 6 yearsThe question asks for the conversion in Java code, not Scala code.
-
rasen58 over 6 yearsAh my mistake, I knew I found it strange that no one had suggested this solution yet - makes sense now.
-
Decoded about 5 yearsJust added an anonymous edit to this point to use the new JavaConverters class (since 2.8.1). Hopefully will be approved.
-
Chris Martin about 5 years@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
. -
Decoded about 5 yearsThanks! Love to be on the cutting edge :D