- Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
- Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
- Set has various methods to add, remove clear, size, etc to enhance the usage of this interface
(Please note that we have entered a duplicate entity but it is not displayed in the output. Also, we can directly sort the entries by passing the unordered Set in as the parameter of TreeSet).
Set output without the duplicates[Geeks, Example, For, Set] Sorted Set after passing into TreeSet[Example, For, Geeks, Set]
Note: As we can see the duplicate entry “Geeks” is ignored in the final output, Set interface doesn’t allow duplicate entries.
Now we will see some of the basic operations on the Set i.e. Union, Intersection and Difference.
Let’s take an example of two integer Sets:
- [1, 3, 2, 4, 8, 9, 0]
- [1, 3, 7, 5, 4, 0, 7, 5]
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.
Union : [0, 1, 2, 3, 4, 5, 7, 8, 9]
We just need to retain the common values from both Sets.
Intersection : [0, 1, 3, 4]
We just need to remove all the values of one Set from the other.
Difference : [2, 8, 9]
Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9] Intersection of the two Set[0, 1, 3, 4] Difference of the two Set[2, 8, 9]
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above