ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

How to convert Java Set to String in Scala?

Here, we will learn about the conversion of Java set to Scala string with example.
Submitted by Shivang Yadav, on February 05, 2021

Java Set is a collection of objects in java in which no two elements can have the same values i.e., no duplicates are allowed.

String is an immutable collection that stores sequences of characters.

Scala programming language has a plus point that it can used java’s functions and data in its program as its build on it. This helps us to convert java set to string in Scala.

How to convert java set to string in Scala?

We can perform this conversion operation by using the toString method present in java in Scala program. This is done by importing the javaConversions object present in Scala library.

Syntax:

javaSet.toString

Program to show the working of the method

import scala.collection.JavaConversions._

object myObject { 
    def main(args:Array[String]) {
        val JavaSet = new java.util.HashSet[Int]() 
        JavaSet.add(4535) 
        JavaSet.add(2003) 
        JavaSet.add(111) 
        
        val scalaString = JavaSet.toString 
        println("The string conversion of java set is " + scalaString) 
    } 
} 

Output:

The string conversion of java set is [111, 2003, 4535]

Program 2:

import scala.collection.JavaConversions._

object myObject { 
    def main(args:Array[String]) {
        val JavaSet = new java.util.HashSet[Int]() 
        JavaSet.add(32) 
        JavaSet.add(100)
        JavaSet.add(111)
        JavaSet.add(100) 
        
        val scalaString = JavaSet.toString 
        println("The string conversion of java set is " + scalaString) 
    } 
} 

Output:

The string conversion of java set is [32, 100, 111]
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.