I need to implement a method that returns a Scala Seq
, in Java.
But I encounter this error:
java.util.ArrayList cannot be cast to scala.collection.Seq
Here is my code so far:
@Override public Seq<String> columnNames() { List<String> a = new ArrayList<String>(); a.add("john"); a.add("mary"); Seq<String> b = (scala.collection.Seq<String>) a; return b; }
But scala.collection.JavaConverters
doesn't seem to offer the possibility to convert as a Seq
.
A java list can be converted to sequence in Scala by utilizing toSeq method of Java in Scala. Here, you need to import Scala's JavaConversions object in order to make this conversions work else an error will occur.
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.
public final class Seq<A> extends java.lang.Object implements java.lang.Iterable<A> Provides an immutable finite sequence, implemented as a finger tree. This structure gives O(1) access to the head and tail, as well as O(log n) random access and concatenation of sequences.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With