Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 649
Cacho Santa Avatar asked Jul 19 '13 03:07

Cacho Santa


People also ask

Can we convert Scala code to Java?

Decompile Scala code to Java In the Project tool window, right-click a Scala library class that you want to decompile. From the context menu, select Decompile Scala to Java. IntelliJ IDEA converts code to Java and opens the converted file in the editor.

What is the difference between SEQ and list in Scala?

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.

What is SEQ in Java?

Seq is a trait which represents indexed sequences that are guaranteed immutable. You can access elements by using their indexes. It maintains insertion order of elements. Sequences support a number of methods to find occurrences of elements or subsequences. It returns a list.

What is Scala seq?

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.


1 Answers

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); } 
like image 78
Chris Martin Avatar answered Sep 21 '22 00:09

Chris Martin