How to convert a Java list of characters to Traversable in Scala?

Here, we will learn to convert a java list of characters to Traversable in Scala. We will see methods and examples to perform the conversion.
Submitted by Shivang Yadav, on January 08, 2021

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.

List in java is an ordered collection.

List of characters is a list that consists of characters as its elements.


[h, e, l, l, o]

Traversable in Scala is a trait with abstract operation which is foreach.


buffer[h, e, l, l, o]

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.



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]() 
        println("The content of java character list is " + javaCharList)		
        val ScalaTraversable = javaCharList.toTraversable 
        println("The traversable conversion is " + ScalaTraversable) 


The content of java character list is [h, e, l, l, o]
The string traversable is buffer[h, e, l, l, o]

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.