Set in Java - GeeksforGeeks
Set in Java - GeeksforGeeks
Set in Java
Read Discuss Practice
The set interface is present in java.util package and extends the Collection
interface. It is an unordered collection of objects in which duplicate values
cannot be stored. It is an interface that implements the mathematical set. This
interface contains the methods inherited from the Collection interface and
adds a feature that restricts the insertion of the duplicate elements. There are
two interfaces that extend the set implementation namely SortedSet and
NavigableSet.
In the above image, the navigable set extends the sorted set interface. Since a
set doesn’t retain the insertion order, the navigable set interface provides the
implementation to navigate through the Set. The class which implements the
navigable set is a TreeSet which is an implementation of a self-balancing tree.
Therefore, this interface provides us with a way to navigate through this tree.
Real-Time Job
Projects Assistance
Method Description
This method is used to remove all the elements from the set
clear()
but not delete the set. The reference for the set still exists.
Method Description
This method is used to retain all the elements from the set
retainAll(collection) which are mentioned in the given collection. This method
returns true if this set changed as a result of the call.
This method is used to get the size of the set. This returns
size()
an integer value which signifies the number of elements.
// Main class
public class GFG {
Output
The set interface allows the users to perform the basic mathematical operation
on the set. Let’s take two arrays to understand these basic operations. Let set1
= [1, 3, 2, 4, 8, 9, 0] and set2 = [1, 3, 7, 5, 4, 0, 7, 5]. Then the possible
operations on the sets are:
1. Intersection: This operation returns all the common elements from the
given two sets. For the above two sets, the intersection would be:
Intersection = [0, 1, 3, 4]
2. Union: This operation adds all the elements in one set with the other. For
the above two sets, the union would be:
Union = [0, 1, 2, 3, 4, 5, 7, 8, 9]
3. Difference: This operation removes all the values present in one set from
the other set. For the above two sets, the difference would be:
Difference = [2, 8, 9]
Example:
Java
// Main class
public class SetExample {
b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
// To find union
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);
Output
1. Adding elements
2. Accessing elements
3. Removing elements
4. Iterating elements
5. Iterating through Set
In order to add an element to the Set, we can use the add() method. However,
the insertion order is not retained in the Set. Internally, for every element, a
hash is generated and the values are stored with respect to the generated
hash. the values are compared and sorted in ascending order. We need to keep
a note that duplicate elements are not allowed and all the duplicate elements
are ignored. And also, Null values are accepted by the Set.
Example
Java
// Main class
class GFG {
Output
[A, B, C]
After adding the elements, if we wish to access the elements, we can use
inbuilt methods like contains().
Example
Java
// Main class
class GFG {
// Declaring a string
String check = "D";
Output
Set is [A, B, C]
Contains D false
The values can be removed from the Set using the remove() method.
Example
Java
// Main class
class GFG {
Output
There are various ways to iterate through the Set. The most famous one is to
use the enhanced for loop.
Example
Java
// Java Program to Demonstrate Working of Set by
// Iterating through the Elements
// Main class
class GFG {
System.out.println();
}
}
Output
A, B, C, D, E,
Classes that implement the Set interface in Java Collections can be easily
perceived from the image below as follows and are listed as follows:
HashSet
EnumSet
LinkedHashSet
TreeSet
Class 1: HashSet
Example
Java
// Main class
class GFG {
System.out.println(i.next());
}
}
Output
Class 2: EnumSet
Java
Output
Class 3: LinkedHashSet
Example
Java
class GFG {
Output
Class 4: TreeSet
Example
Java
// Main class
class GFG {
while (i.hasNext())
System.out.println(i.next());
}
}
Output
Whether you're preparing for your first job interview or aiming to upskill in this
ever-evolving tech landscape, GeeksforGeeks Courses are your key to success.
We provide top-quality content at affordable prices, all geared towards
accelerating your growth in a time-bound manner. Join the millions we've
already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Similar Reads
Difference Between Program to Convert Set of
java.sql.Time, Integer to Set of String in
java.sql.Timestamp and… Java
Related Tutorials
Java AWT Tutorial Spring MVC Tutorial
Next
Article Contributed By :
GeeksforGeeks
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Apply for Mentor
Commerce UPSC
Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Human Resource Management (HRM) Science and Technology Notes
Management Economics Notes
Income Tax Important Topics in Ethics
Finance UPSC Previous Year Papers
Statistics for Economics