Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java List to Scala Seq

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.

like image 585
Fundhor Avatar asked Mar 14 '16 13:03

Fundhor


People also ask

How to convert list into Seq in Scala?

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.

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?

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.

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

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(); } 
like image 113
Fundhor Avatar answered Oct 16 '22 14:10

Fundhor