Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Scala List from Java List?

Tags:

java

scala

People also ask

Can I use Java list in Scala?

A java list can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala's JavaConversions object in order to make this conversions work. Now, lets see some examples.

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.

How do you define a list in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.


EDIT: Note that this is deprecated since 2.12.0. Use JavaConverters instead. (comment by @Yaroslav)

Since Scala 2.8 this conversion is now built into the language using:

import scala.collection.JavaConversions._

...

lst.toList.foreach{ node =>   .... }

works. asScala did not work

In 2.12.x use import scala.collection.JavaConverters._

In 2.13.x use import scala.jdk.CollectionConverters._


There's a handy Scala object just for this - scala.collection.JavaConverters

You can do the import and asScala afterwards as follows:

import scala.collection.JavaConverters._

val lst = node.getByXPath(xpath).asScala
lst.foreach{ node =>   .... }

This should give you Scala's Buffer representation allowing you to accomplish foreach.


I was looking for an answer written in Java and surprisingly couldn't find any clean solutions here. After a while I was able to figure it out so I decided to add it here in case someone else is looking for the Java implementation (I guess it also works in Scala?):

JavaConversions.asScalaBuffer(myJavaList).toList()

If you have to convert a Java List<ClassA> to a Scala List[ClassB], then you must do the following:

1) Add

import scala.collection.JavaConverters._

2) Use methods asScala, toList and then map

List <ClassA> javaList = ...
var scalaList[ClassB] = javaList.asScala.toList.map(x => new ClassB(x))

3) Add the following to the ClassB constructor that receives ClassA as a parameter:

case class ClassB () {
   def this (classA: ClassA) {
      this (new ClassB (classA.getAttr1, ..., classA.getAttrN))
   }
}

Shortcut to convert java list to scala list

import scala.jdk.CollectionConverters._

myjavaList.asScala.toList