How to convert java Set of Shorts to String in Scala?

Here, we will learn methods to convert sets of shorts to strings in Scala with the help of working examples.
Submitted by Shivang Yadav, on January 08, 2021

Java Set is a collection of elements in java that are unique i.e. no duplicate elements are present in the set.

Set of Shorts is the set consisting of all short Int values in it.

Example:

[100, 9, -12, 65]

String in Scala is a collection that stores data in the form of an array of characters.

Example:

"100, 9, -12, 65"

Scala and java programming languages are quite similar as Scala is majorly built over java inheriting many of its features. This results in an amazing thing that you can use java-based collections in Scala and convert them to required one easily for processing.

Here is an example to convert java set of shorts to strings in Scala.

The toString method in Scala taken from java is utilized for performing this conversion. For using this method, you need to import the javaConversion library to your Scala program.

Import statement:

import scala.collection.JavaConversions._

Syntax:

java_Set.toString

Parameter: This method is a parameter less method i.e. it does not accept any parameter with its call.

Returns: The method returns a string which is the string conversion of a set.

Program to illustrate the working of our toString method

import scala.collection.JavaConversions._

object MyClass {
    def main(args: Array[String]) {
        val javaSetShorts = new java.util.HashSet[Short]() 
        
        javaSetShorts.add(65) 
        javaSetShorts.add(541) 
        javaSetShorts.add(-31234) 
        javaSetShorts.add(0) 
        
        println("The content of java Set of Shorts is " + javaSetShorts)		
        
        val scalaString = javaSetShorts.toString 
        println("The string conversion is " + scalaString) 
    }
}

Output:

The content of java Set of Shorts is [65, 541, -31234, 0]
The string conversion is [65, 541, -31234, 0]

Program to illustrate the working of toString method

Here, we will try to feed duplicate elements to the set in Java.

import scala.collection.JavaConversions._

object MyClass {
    def main(args: Array[String]) {
        val javaSetShorts = new java.util.HashSet[Short]() 
        
        javaSetShorts.add(65) 
        javaSetShorts.add(541) 
        javaSetShorts.add(-31234) 
        javaSetShorts.add(0) 
        javaSetShorts.add(-31234) 
        
        println("The content of java Set of Shorts is " + javaSetShorts)		
        
        val str = set.toString 
        println("The string conversion is " + str) 
    }
}

Output:

The content of java Set of Shorts is [65, 541, -31234, 0]
The string conversion is [65, 541, -31234, 0]

The output in both the examples is the same set does not allow duplicate entries.




Comments and Discussions!

Load comments ↻






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