Set in Java
- Set is an interface that 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
filter_none
edit
play_arrow
brightness_4
|
(Please note that we have entered a duplicate entity but it is not displayed in the output. Also, we can directly sort the entries bypassing the unordered Set in as the parameter of TreeSet).
Output:
Set output without the duplicates[Set, Example, Geeks, for] 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]
Union
In this, we could simply add one Set with others. Since the Set will itself not allow any duplicate entries, we need not take care of the common values.
Expected Output:
Union : [0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection
We just need to retain the common values from both Sets.
Expected Output:
Intersection : [0, 1, 3, 4]
Difference
We just need to remove all the values of one Set from the other.
Expected Output:
Difference : [2, 8, 9]
filter_none
edit
play_arrow
brightness_4
|
Output:
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]
post a comment