Set in Java
In Java, the Set interface is a part of the Java Collection
Framework, located in the [Link] package. It represents a
collection of unique elements, meaning it does not allow
duplicate values.
Key Features of Set
No duplicates: Set does not allow duplicate elements;
each item must be unique.
No guaranteed order: Elements in a Set are not stored
or retrieved in any defined order.
Ordering exceptions: LinkedHashSet maintains
insertion order, while TreeSet keeps elements sorted.
One null allowed: Most Set implementations allow only
a single null element.
Collection methods inherited: Set supports standard
methods like add(), remove(), contains(), size() and
iterator() from the Collection interface.
Example: Java Program to Implementing Set Interface
import [Link];
import [Link];
public class Geeks {
public static void main(String args[])
// Create a Set using HashSet
Set<String> s = new HashSet<>();
// Displaying the Set
[Link]("Set Elements: " + s);
Hierarchy of Java Set interface
The image below demonstrates the hierarchy of Java Set
interface.
Performing Various Operations on Set
Set interface provides commonly used operations to manage
unique elements in a collection. These include:
1. Adding elements
2. Accessing elements
3. Removing elements
4. Iterating elements
1. Adding Elements
To add elements to a Set in Java, use the add() method.
Example: This example demonstrates how HashSet stores
unique element and does not maintain any insertion order.
import [Link].*;
// Main class
class Geeks {
public static void main(String[] args)
{
Set<String> s = new HashSet<String>();
[Link]("B");
[Link]("B");
[Link]("C");
[Link]("A");
[Link](s);
}
}
Output
[A, B, C]
2. Accessing the Elements
After adding the elements, if we wish to access the elements, we
can use inbuilt methods like contains().
Example: This example demonstrates how to check if a
specified element exists or not using the contains() method.
import [Link].*;
class Geeks {
public static void main(String[] args)
Set<String> h = new HashSet<String>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("A");
[Link]("Set is " + h);
String s = "D";
[Link]("Contains " + s + " " + [Link](s));
Output
Set is [A, B, C]
Contains D false
3. Removing Elements
The values can be removed from the Set using the remove()
method.
Example: This example demonstrates how to remove element
from a HashSet using remove() method
import [Link].*;
class Geeks {
public static void main(String[] args)
// Declaring object of Set of type String
Set<String> h = new HashSet<String>();
// Elements are added using add() method, Custom input elements
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("B");
[Link]("D");
[Link]("E");
[Link]("Initial HashSet " + h);
// Removing custom element using remove() method
[Link]("B");
[Link]("After removing element " + h);
Output
Initial HashSet [A, B, C, D, E]
After removing element [A, C, D, E]
4. Iterating elements
There are various ways to iterate through the Set. The most famous one is to use
the enhanced for loop.
Example: This example demonstrates how to iterate through a HashSet.
import [Link].*;
class Geeks {
public static void main(String[] args)
// Creating object of Set and declaring String type
Set<String> h = new HashSet<String>();
// Adding elements to Set using add() method, Custom input elements
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("B");
[Link]("D");
[Link]("E");
// Iterating through the Set via for-each loop
for (String value : h)
// Printing all the values inside the object
[Link](value + ", ");
[Link]();
Output
A, B, C, D, E,
Classes that implement the Set interface
1. HashSet: HashSet is a collection class that implements a
hash table-based Set, storing elements based on their hashcode
without maintaining insertion order and allowing one null
element.
2. EnumSet: EnumSet is a specialized Set implementation for
use with enum types. It is part of the Java Collections Framework
and offers high performance, often faster than HashSet. All
elements in an EnumSet must belong to the same enum type,
defined at creation time.
3. LinkedHashSet: LinkedHashSet is an ordered version of
HashSet that maintains insertion order using a doubly-linked list
across all elements.
4. TreeSet: TreeSet is a SortedSet implementation that stores
elements in ascending order using a tree structure, ensuring
natural ordering or a custom comparator.
Methods of Set Interface
Let us discuss methods present in the Set interface provided
below in a tabular format below as follows:
Method Description
Adds element if not already present. Returns
add(element)
true if added.
addAll(collection) Adds all elements from the given collection.
clear() Removes all elements from the set.
Checks if the set contains the specified
contains(element)
element.
containsAll(collectio Checks if the set contains all elements from
n) the given collection.
hashCode() Returns the hash code of the set.
This method is used to check whether the set
isEmpty()
is empty or not.
Method Description
This method is used to return the iterator of
iterator()
the set.
remove(element) Removes the specified element from the set.
removeAll(collectio Removes all elements in the given collection
n) from the set.
Retains only elements present in the given
retainAll(collection)
collection.
size() Returns the number of elements in the set.
This method is used to form an array of the
toArray()
same elements as that of the Set.
Example to Implement Set Using TreeSet
import [Link];
import [Link];
import [Link];
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<>();
try {
for(int i = 0; i < 5; i++) {
[Link](count[i]);
[Link](set);
TreeSet<Integer> sortedSet = new TreeSet<>(set);
[Link]("The sorted list is:");
[Link](sortedSet);
[Link]("The First element of the set is: "+ (Integer)[Link]());
[Link]("The last element of the set is: "+ (Integer)[Link]());
catch(Exception e) {}
Output
[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
Example to Implement Set Using LinkedHashSet
import [Link];
import [Link];
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new LinkedHashSet<>();
try {
for(int i = 0; i < 5; i++) {
[Link](count[i]);
[Link](set);
catch(Exception e) {}
Output
[34, 22, 10, 60, 30]
Example to Implement Set Using EnumSet
// Creating an EnumSet
import [Link];
enum Student { Geek1, Geek2, Geek3, Geek4, Geek5 }
public class Geeks {
public static void main(String[] args) {
// Create an EnumSet containing specific elements
EnumSet<Student> e = [Link](Student.Geek1, Student.Geek2, Student.Geek3);
[Link]("EnumSet: " + e);
Output
EnumSet: [Geek1, Geek2, Geek3]