Harita Parmar
Harita Parmar

Reputation: 85

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?

Upvotes: 4

Views: 14600

Answers (2)

Basapuram Kumar
Basapuram Kumar

Reputation: 179

Below code works for me:

applcation.conf

mydata.crypto {

ciphers = [

           "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"

           "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"

           "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"

          ]

 protocols = [

               "TLSv1.2"

             ]

   }

Sample code in scala Reading as List:

val ciphersList = config.getStringList("mydata.crypto.ciphers")

val protocolsList = config.getStringList("mydata.crypto.protocols")

import scala.collection.JavaConverters._

val enableCiphersList = ciphersList.asScala.toArray

val enableProtocolsList = protocolsList.asScala.toArray

Now we can see "enableCiphersList" and "enableProtocolsList" are Array of Strings type.

Upvotes: -1

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

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

Upvotes: 9

Related Questions