Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Scala program to add all Array elements to a Set object. We can use array.toSet() method or Set.apply() method to add all the elements of an Array to Set object.
Set has apply() method which accepts Repeated parameters to add multiple elements. If you are not familiar with Repeated Parameters, please go through the below article again:
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.clearurdoubt object SetDemo { def main(args: Array[String]) { val array = Array(1,2,3,1,2,3,4) val set1 = Set.apply(array: _*) val set2 = array.toSet println("Set1 Elements: " + set1.mkString(",")) println("Set2 Elements: " + set2.mkString(",")) } } |
Output:
Happy Learning.
Please leave a reply in case of any queries.