Home »
Scala
How to convert a Java list of characters to Traversable in Scala?
By IncludeHelp Last updated : October 20, 2024
Overview
As we know Scala is based on java which makes the interoperation between both a lot easier. Also, it inherits features from Scala that enables the usage and conversion of java data structures in Scala easy.
Java List
List in java is an ordered collection.
List of characters is a list that consists of characters as its elements.
Example
[h, e, l, l, o]
Traversable in Scala
Traversable in Scala is a trait with abstract operation which is foreach.
Example
buffer[h, e, l, l, o]
Convert Java data types to another data type
In Scala, we can convert java data types to another data type in Scala. The conversion from java list of characters to traversable in Scala is done using toTraverable method.
Syntax
javaList.toTraversable
Parameter
The method is a parameter less method i.e. it does not accept any parameter.
Return type
It returns a traversable trait in Scala.
Program to illustrate the conversion of toTraversable in Scala
import scala.collection.JavaConversions._
object MyClass {
def main(args: Array[String]) {
val javaCharList = new java.util.ArrayList[Char]()
javaCharList.add('H')
javaCharList.add('e')
javaCharList.add('l')
javaCharList.add('l')
javaCharList.add('o')
println("The content of java character list is " + javaCharList)
val ScalaTraversable = javaCharList.toTraversable
println("The traversable conversion is " + ScalaTraversable)
}
}
Output
The content of java character list is [h, e, l, l, o]
The string traversable is buffer[h, e, l, l, o]