Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java list to array in scala?

How to convert java.util.list[POJO] to Scala array[POJO]? I tried list.toArray method but it gives array[object]. Can anyone help on this?

like image 392
Harita Parmar Avatar asked Aug 31 '25 21:08

Harita Parmar


1 Answers

You have to create the target array first, and provide it as input for the toArray method:

list.toArray(Array.ofDim[POJO](list.size))

This API shifts all the problems with array instantiation from the toArray method to you, so it is your responsibility to make sure that POJO is either something concrete, or to provide a ClassTag.


You could also do the conversion in two steps, first using asScala from JavaConverters:

import scala.collection.JavaConverters._

and then invoking .toArray from the Scala API (unlike Java's API, it preserves the type):

list.asScala.toArray
like image 88
Andrey Tyukin Avatar answered Sep 03 '25 11:09

Andrey Tyukin