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]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.