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?
-
1Can you tell me the structure of your pojo?Raman Mishra– Raman Mishra2018-04-14 15:10:32 +00:00Commented Apr 14, 2018 at 15:10
-
Try importing javaConverters and do list.asScala it should workRaman Mishra– Raman Mishra2018-04-14 15:12:55 +00:00Commented Apr 14, 2018 at 15:12
-
1Yeah..It works!Harita Parmar– Harita Parmar2018-04-16 13:54:33 +00:00Commented Apr 16, 2018 at 13:54
2 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
Comments
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.