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

4 Answers 4

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

4 Comments

I'm not able to import scala.collection.JavaConversions; in eclipse. its showing Error here
Not sure if this is new or not but I had to do seqAsJavaList(seq).asJava to get the actual List<E>
Just added an anonymous edit to this point to use the new JavaConverters class (since 2.8.1). Hopefully will be approved.
@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.
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);
    }
}

1 Comment

It might be a good idea for scala to provide a more java-friendly set of frontend methods for these kinds of conversions.
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")

Comments

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

2 Comments

The question asks for the conversion in Java code, not Scala code.
Ah my mistake, I knew I found it strange that no one had suggested this solution yet - makes sense now.

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.