Convert Java List to Scala Seq

对着背影说爱祢 提交于 2019-11-28 09:44:05

JavaConverters is what I needed to solve this.

import scala.collection.JavaConverters;

public Seq<String> convertListToSeq(List<String> inputList) {
    return JavaConverters.asScalaIteratorConverter(inputList.iterator()).asScala().toSeq();
}

JavaConversions should work. I think, you are looking for something like this: JavaConversions.asScalaBuffer(a).toSeq()

Neeleshkumar Srinivasan Mannur

@Fundhor, the method asScalaIterableConverter was not showing up in the IDE. It may be due to a difference in the versions of Scala. I am using Scala 2.11. Instead, it showed up asScalaIteratorConverter. I made a slight change to your final snippet and it worked fine for me.

scala.collection.JavaConverters.asScalaIteratorConverter(columnNames.iterator()).asScala().toSeq() where columnNames is a java.util.List.

thanks !

This worked for me! (Java 8, Spark 2.0.0)

import java.util.ArrayList;

import scala.collection.JavaConverters;
import scala.collection.Seq;

public class Java2Scala
{

    public Seq<String> getSeqString(ArrayList<String> list)
        {
            return JavaConverters.asScalaIterableConverter(list).asScala().toSeq();
        }

}

Up to 4 elements, you can simply use the factory method of the Seq class like this :

Seq<String> seq1 =  new Set.Set1<>("s1").toSeq();
Seq<String> seq2 =  new Set.Set2<>("s1", "s2").toSeq();
Seq<String> seq3 =  new Set.Set3<>("s1", "s2", "s3").toSeq();
Seq<String> seq4 =  new Set.Set4<>("s1", "s2", "s3", "s4").toSeq();

Starting Scala 2.13, package scala.jdk.javaapi.CollectionConverters replaces deprecated packages scala.collection.JavaConverters/JavaConversions:

import scala.jdk.javaapi.CollectionConverters;

// List<String> javaList = Arrays.asList("a", "b");
CollectionConverters.asScala(javaList).toSeq();
// Seq[String] = List(a, b)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!