- 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[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]
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]
This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.util.Collections.disjoint() Method in java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.lang.Short toString() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java.util.concurrent.Phaser class in Java with Examples