Convert from scala.collection.Seq<String> to java.util.List<String> in Java code

天大地大妈咪最大 提交于 2019-11-28 08:05:57

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);
}
4lex1v

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);
    }
}

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")

(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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!