Home »
Scala
How to convert Java Set to String in Scala?
By IncludeHelp Last updated : November 14, 2024
Java Set
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.
Scala Strings
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.
Convert Java Set to String
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
Example to Convert Java Set to String
import scala.jdk.CollectionConverters._
object myObject {
def main(args: Array[String]): Unit = {
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]
Example 2
import scala.jdk.CollectionConverters._
object myObject {
def main(args: Array[String]): Unit = {
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]