Set in Scala
Like set in Python, A set in Scala is an unordered collection of distinct elements.
Set in Python is mutable, Scala has immutable and mutable sets. By default, Set in Scala is equal to scala.collection.immutable.Set, which is immutable
You can create a set by using Set(), you can convert to set by toSet method
1
//Create a set if you know elements
2
val s0=Set(1,2,3,4)
3
// s0: scala.collection.mutable.Set[Int] = Set(1, 2, 3, 4)
4
//Create an empty set
5
import scala.collection.mutable.Set
6
val s1:scala.collection.mutable.Set[Int]=Set()
7
//s1: scala.collection.mutable.Set[Int] = Set()
8
//Add elements to a set
9
val s2:scala.collection.mutable.Set[Int]=s1 + 1 +2 +3 +4
10
//s2: scala.collection.mutable.Set[Int] = Set(1, 2, 3, 4)
Copied!
Last modified 1yr ago
Copy link