Knoldus Blog Audio
Collections in Scala systematically distinguish between mutable and immutable collections. In the previous blog, we had covered –
- An Overview of Collections and its types in Scala
- (Im)Mutability in Scala
You may go through the Collections And (Im)Mutability in Scala (Part-1). So, In this Blog we will discuss Scala Set in detail.
Scala Sets are iterables that does not contain any duplicate element. Also, such type of collection does not maintain the order of elements being stored in it.
In Scala, Sets can be mutable and immutable. But, the difference between these two’s is just when an object is immutable it can’t be changed. By default, Scala uses immutable Sets.
A number of operations can be operated on sets in Scala. They can be summarized as follows –
1. Test –
subsetOf like operations that returns a Boolean value.
containswill check for an element whether it exists in Set or not.
applywill try to add an element to Set, as Set is immutable by default so you have to declare them mutable to add element.
- subsetOf will check whether the Set is a subset of the other given Set returning a boolean value.
2. Addition –
++ adding one or more element to Set yielding a new Set.
3. Removal –
-- removing one or more element, yielding a new Set.
4. Set Operations –
Set operations such as Union , Intersection ,and Set Difference exists in two form i.e. Symbolic and alphabetical.
Set Difference –>
Let’s discuss about all its types and try to perform some basic operations.
1) TreeSet –
Although the Set does not guarantee the ordering of the elements but TreeSet will make the elements in the given order. TreeSet is an abstract class.
2) SortedSet –
Scala SortedSet, a collection that produces its elements either using iterator or foreach in a given ordering i.e. they can be freely chosen at the time the set is created.
3) HashSet –
Scala HashSet is a sealed class that extends Abstract Set and immutable Set Traits. Thus, such type of collection uses hash codes to store elements.
4) BitSet –
Scala BitSet is sets of non-negative integers extending the set trait which are represented as variable-size arrays of bits packed into 64-bit words. In fact the memory footprint of a bitset is determined by the largest number stored in it.
As, the Bitset doesn’t accept the negative numbers thus while storing a non positive integer to it leads to a IllegalArgumentException.
5) ListSet –
Scala ListSet extends immutable sets using a list-based data structure. In it, the elements are stored in reversed order, so the newest will be at top/head of the list maintaining the insertion order.
In this blog we have covered Scala Set and it’s following types-
Again, for Best Practice, start immutable and know the performance characteristics.
In this blog, we have gone through the Set and some basic operations which we can apply on Set in Scala. Stay tuned for the next part of Collections in Scala, where we’ll discuss Sequence in detail. You don’t wanna miss it….