ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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.

Example:

[h, e, l, l, o]

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

Example:

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.

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]
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.