Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set in immutable collection. Example 1:
Scala
// Scala program to illustrate how to
// add items using +=, ++== and add()
// method in mutable set with mutable
// collection
import scala.collection.mutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing set
var myset = Set("G", "Geek", "for")
println("Set before addition "+
"of new elements:")
println(myset)
// Adding new element in set
// using += and ++==
myset += "Geeks"
// Here, "G" is already present in the
// Set so, "G" is not added in set
myset ++== List("Geeks12", "geek23", "G")
// Adding elements using add() method
myset.add("GeeksforGeeks")
myset.add("geeksForgeeks100")
println("\nSet after addition of new elements:")
println(myset)
}
}
Output:
Set before addition of new elements:
Set(for, G, Geek)
Set after addition of new elements:
Set(geek23, for, Geeks, G, Geek, Geeks12, geeksForgeeks100, GeeksforGeeks)
Example 2:
Scala
// Scala program to illustrate how
// to add items using += operator in
// mutable set with immutable collection
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing mutable set
var myset = Set("G", "Geek", "for")
println("Set before addition" +
" of new elements:")
println(myset)
// Adding new element in set
// using += operator
myset += "GeeksforGeeks"
myset += "geeks1000"
println("\nSet after addition " +
"of new elements:")
println(myset)
}
}
Output:
Set before addition of new elements:
Set(G, Geek, for)
Set after addition of new elements:
Set(for, Geek, G, geeks1000, GeeksforGeeks)
Removing elements from the Mutable setIn Set, We can only remove elements in the mutable set. -= and --= methods are used to delete elements and we can also use retain(), clear(), and remove() methods to delete elements when we are working with mutable set in the mutable collection. -= operator is used to delete elements when we are working with mutable set in immutable collection. Example 1:
Scala
// Scala program to illustrate
// how to delete items using -=
// and --= methods in mutable set
// with mutable collection
import scala.collection.mutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing
//mutable set
var myset = Set(100, 400, 500,
600, 300, 800)
println("Set before deletion:")
println(myset)
// Deleting elements in set
// using -= and --= methods
myset -= 600
myset --= List(300, 100)
println("\nSet after deletion:")
println(myset)
}
}
Output:
Set before deletion:
Set(300, 100, 800, 500, 600, 400)
Set after deletion:
Set(800, 500, 400)
Example 2:
Scala
// Scala program to illustrate
// how to delete items using
// retain(), and clear() methods
// in mutable set with mutable
// collection
import scala.collection.mutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing
// mutable set
var myset1 = Set(100, 400, 500,
600,300, 800)
var myset2 = Set(11, 44, 55, 66, 77)
println("Set before deletion:")
println(myset1)
println(myset2)
// Deleting elements in set
// using retain() method
myset1.retain(_>500)
println("\nSet after using retain()" +
" method:")
println(myset1)
// Deleting elements in set
// using clear() method
myset2. clear
println("\nSet after using clear() method:")
println(myset2)
}
}
Output:
Set before deletion:
Set(300, 100, 800, 500, 600, 400)
Set(66, 55, 11, 44, 77)
Set after using retain() method:
Set(800, 600)
Set after using clear() method:
Set()
Adding items in immutable SetIn immutable set, We cannot add elements, but we can use + and ++ operators to add element from the immutable set and store the result into a new variable. Here, + is used to add single or multiple elements and ++ is used to add multiple elements defined in another sequence and in concatenation of immutable set. Example:
Scala
// Scala program to illustrate how
// to add elements in immutable set
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing
// immutable set
val myset1 = Set(100, 400, 500,
600,300, 800)
val myset2 = Set(11, 44, 55, 66, 77)
println("Set before addition:")
println(myset1)
println(myset2)
println("\nSet after addition:")
// Add single element in myset1
// and create new Set
val S1 = myset1 + 900
println(S1)
// Add multiple elements in myset1
// and create new Set
val S2 = myset1 + (200, 300)
println(S2)
// Add another list into myset1
// and create new Set
val S3 = myset1 ++ List(700, 1000)
println(S3)
// Add another set myset2 into
// myset1 and create new Set
val S4 = myset1 ++ myset2
println(S4)
}
}
Output:
Set before addition:
Set(500, 600, 800, 300, 400, 100)
Set(77, 44, 66, 11, 55)
Set after addition:
Set(500, 900, 600, 800, 300, 400, 100)
Set(500, 600, 800, 300, 400, 200, 100)
Set(500, 700, 1000, 600, 800, 300, 400, 100)
Set(500, 77, 44, 66, 600, 11, 55, 800, 300, 400, 100)
Removing elements from the immutable setIn immutable set, We cannot remove elements, but we can use - and -- operators to remove elements from the immutable set and store the result into a new variable. Here, - operator is used to remove one or more elements and -- operator is used to remove multiple elements defined in another sequence. Example:
Scala
// Scala program to illustrate how
// to remove elements in immutable set
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing
// immutable set
val myset = Set(100, 400, 500, 600,
300, 800, 900, 700)
println("Set before deletion:")
println(myset)
println("\nSet after deletion:")
// Remove single element in myset and
// Result store into new variable
val S1 = myset - 100
println(S1)
// Remove multiple elements from myset
// Result store into new variable
val S2 = myset - (400, 300)
println(S2)
// Remove another list from myset
// Result store into new variable
val S3 = myset -- List(700, 500)
println(S3)
}
}
Output:
Set before deletion:
Set(500, 900, 700, 600, 800, 300, 400, 100)
Set after deletion:
Set(500, 900, 700, 600, 800, 300, 400)
Set(500, 900, 700, 600, 800, 100)
Set(900, 600, 800, 300, 400, 100)
Set OperationsNow we will see some of the basic mathematical operations on the Set like Union, Intersection, and Difference.
- Union: In this, we could simply add one Set with other. Since the Set will itself not allow any duplicate entries, we need not take care of the common values. To perform union, we use union() method.
- Intersection: To get the common values from both Sets we use intersect() method. It returns a new set which contains all the common values present in both sets.
- Difference: To get the difference of two Sets we use diff() method. It returns the set which contains all the that are not present in myset2.
Example:
Scala
// Scala program to illustrate union,
// intersection, and difference on Set
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing set
val myset1 = Set(11, 22, 33, 44,
55, 66, 77, 111)
val myset2 = Set(88, 22, 99, 44,
55, 66, 77)
// To find intersection
val S1 = myset1.intersect(myset2)
println("Intersection:")
println(S1)
// To find the symmetric difference
val S2 = myset1.diff(myset2)
println("\nDifference:")
println(S2)
// To find union
val S3 = myset1.union(myset2)
println("\nUnion:")
println(S3)
}
}
Output:
Intersection:
Set(77, 22, 44, 66, 55)
Difference:
Set(33, 11, 111)
Union:
Set(88, 33, 77, 22, 44, 66, 11, 99, 55, 111)
Similar Reads
Collections
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents
5 min read
A list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built u
6 min read
A set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen
6 min read
Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: m
5 min read
Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr
6 min read
Array in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size canât change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala.collection.mutable.ArrayBuf
4 min read
Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
5 min read
A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite
3 min read
Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i
7 min read
A set is a collection which only contains unique items which are not repeatable. A BitSet is a collection of small integers as the bits of a larger integer. Non negative integers sets which represented as array of variable-size of bits packed into 64-bit words is called BitSets. The largest number s
5 min read
HashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic
4 min read
A stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, v
3 min read
HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map. Syntax: var hashMapName = HashMap("key1"->"value1", "key2"->"value
3 min read
Set is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions: scala.collection.immutable.TreeSet and scala.collection.mutable.TreeSet. Syntax
4 min read
An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther
5 min read
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The insta
3 min read