![]() |
VOOZH | about |
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:
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:
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:
Output:
Set before deletion: Set(300, 100, 800, 500, 600, 400) Set after deletion: Set(800, 500, 400)
Example 2:
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:
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:
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.
Example:
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)