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 adds a feature that restricts the insertion of duplicate elements.
- No Specific Order: Does not maintain any specific order of elements (Exceptions: LinkedHashSet and TreeSet).
- Allows One Null Element: Most Set implementations allow a single null element.
- Implementation Classes: HashSet, LinkedHashSet, and TreeSet.
- Thread-Safe Alternatives: For thread-safe operations, use
ConcurrentSkipListSet or wrap a set using Collections.synchronizedSet().
Two interfaces extend the set implementation, that are, SortedSet and NavigableSet.
Example: This example demonstrates how to create an empty HashSet.
Java
// Java Program to Implementing Set Interface
import java.util.HashSet;
import java.util.Set;
public class Geeks {
public static void main(String args[])
{
// Create a Set using HashSet
Set<String> s = new HashSet<>();
// Displaying the Set
System.out.println("Set Elements: " + s);
}
}
Explanation: In the above example, HashSet will appear as an empty set, as no elements were added. The order of elements in HashSet is not guaranteed, so the elements will be displayed in a random order if any are added.
Hierarchy of Java Set interface
The image below demonstrates the hierarchy of Java Set interface.
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.
Declaration of Set Interface
The declaration of Set interface is listed below:
public interface Set extends Collection
Creating Set Objects:
Since Set is an interface, objects cannot be created of the typeset. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. This type-safe set can be defined as:
// Obj is the type of the object to be stored in Set
Set<Obj> set = new HashSet<Obj> ();
Methods
Let us discuss methods present in the Set interface provided below in a tabular format below as follows:
| Method | Description |
|---|
| add(element) | This method is used to add a specific element to the set. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set. |
| addAll(collection) | This method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order. |
| clear() | This method is used to remove all the elements from the set but not delete the set. The reference for the set still exists. |
| contains(element) | This method is used to check whether a specific element is present in the Set or not. |
| containsAll(collection) | This method is used to check whether the set contains all the elements present in the given collection or not. This method returns true if the set contains all the elements and returns false if any of the elements are missing. |
| hashCode() | This method is used to get the hashCode value for this instance of the Set. It returns an integer value which is the hashCode value for this instance of the Set. |
| isEmpty() | This method is used to check whether the set is empty or not. |
| iterator() | This method is used to return the iterator of the set. The elements from the set are returned in a random order. |
| remove(element) | This method is used to remove the given element from the set. This method returns True if the specified element is present in the Set otherwise it returns False. |
| removeAll(collection) | This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call. |
| retainAll(collection) | This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call. |
| size() | This method is used to get the size of the set. This returns an integer value which signifies the number of elements. |
| toArray() | This method is used to form an array of the same elements as that of the Set. |
Example: Sample Program to Illustrate Set interface
Java
// Java program Illustrating Set Interface
// Importing utility classes
import java.util.*;
// Main class
public class Geeks {
// Main driver method
public static void main(String[] args)
{
// Demonstrating Set using HashSet
// Declaring object of type String
Set<String> s = new HashSet<String>();
// Adding elements to the Set
// using add() method
s.add("Geeks");
s.add("For");
s.add("Geeks");
s.add("Example");
s.add("Set");
// Printing elements of HashSet object
System.out.println(s);
}
}
Output[Set, Example, Geeks, For]
Explanation: In the above example, we can see the elements are in random order as HashSet does not maintain any order and duplicate elements are automatically ignored in HashSet.
Operations on the Set Interface
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]
Now, let us implement the following operations as defined above as follows:
Example: This example demonstrates how to perform various operations on set.
Java
// Java Program Demonstrating Operations on the Set
// such as Union, Intersection and Difference operations
// Importing all utility classes
import java.util.*;
// Main class
public class Geeks {
// Main driver method
public static void main(String args[])
{
// Creating an object of Set class
// Declaring object of Integer type
Set<Integer> a = new HashSet<Integer>();
// Adding all elements to List
a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
// Again declaring object of Set class
// with reference to HashSet
Set<Integer> b = new HashSet<Integer>();
b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
// To find union
Set<Integer> u = new HashSet<Integer>(a);
u.addAll(b);
System.out.print("Union of the two Set");
System.out.println(u);
// To find intersection
Set<Integer> i = new HashSet<Integer>(a);
i.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(i);
// To find the symmetric difference
Set<Integer> d = new HashSet<Integer>(a);
d.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(d);
}
}
OutputUnion 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]
Performing Various Operations on SortedSet
After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. Since Set is an interface, it can be used only with a class that implements this interface. HashSet is one of the widely used classes which implements the Set interface. Now, let’s see how to perform a few frequently used operations on the HashSet. We are going to perform the following operations as follows:
- Adding elements
- Accessing elements
- Removing elements
- Iterating elements
- Iterating through Set
Now let us discuss these operations individually as follows:
1. Adding Elements
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: This example demonstrates how HashSet stores unique element and does not maintain any insertion order.
Java
// Java Program Demonstrating Working of Set by
// Adding elements using add() method
// Importing all utility classes
import java.util.*;
// Main class
class Geeks {
// Main driver method
public static void main(String[] args)
{
// Creating an object of Set and
// declaring object of type String
Set<String> s = new HashSet<String>();
// Adding elements to above object
// using add() method
s.add("B");
s.add("B");
s.add("C");
s.add("A");
// Printing the elements inside the Set object
System.out.println(s);
}
}
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.
Java
// Java code to demonstrate Working of Set by
// Accessing the Elements of the Set object
// Importing all utility classes
import java.util.*;
// Main class
class Geeks {
// Main driver method
public static void main(String[] args)
{
// Creating an object of Set and
// declaring object of type String
Set<String> h = new HashSet<String>();
// Elements are added using add() method
// Later onwards we will show accessing the same
// Custom input elements
h.add("A");
h.add("B");
h.add("C");
h.add("A");
// Print the Set object elements
System.out.println("Set is " + h);
// Declaring a string
String s = "D";
// Check if the above string exists in
// the SortedSet or not
// using contains() method
System.out.println("Contains " + s + " "
+ h.contains(s));
}
}
OutputSet is [A, B, C]
Contains D false
3. Removing the Values
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
Java
// Java Program Demonstrating Working of Set by
// Removing Element/s from the Set
// Importing all utility classes
import java.util.*;
// Main class
class Geeks {
// Main driver method
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
h.add("A");
h.add("B");
h.add("C");
h.add("B");
h.add("D");
h.add("E");
// Printing initial Set elements
System.out.println("Initial HashSet " + h);
// Removing custom element
// using remove() method
h.remove("B");
// Printing Set elements after removing an element
// and printing updated Set elements
System.out.println("After removing element " + h);
}
}
OutputInitial HashSet [A, B, C, D, E]
After removing element [A, C, D, E]
4. Iterating through the Set
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.
Java
// Java Program to Demonstrate Working of Set by
// Iterating through the Elements
// Importing utility classes
import java.util.*;
// Main class
class Geeks {
// Main driver method
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
h.add("A");
h.add("B");
h.add("C");
h.add("B");
h.add("D");
h.add("E");
// Iterating through the Set
// via for-each loop
for (String value : h)
// Printing all the values inside the object
System.out.print(value + ", ");
System.out.println();
}
}
Classes that implement the Set interface in Java Collections can be easily perceived from the image below as follows and are listed as follows:
Hierarchy of Java Collections
Class 1: HashSet
HashSet class which is implemented in the collection framework is an inherent implementation of the hash table data structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s see how to create a set object using this class.
Example: This example demonstrates how to add, remove, and iterate through elements in a HashSet.
Java
// Java program Demonstrating Creation of Set object
// Using the Hashset class
// Importing utility classes
import java.util.*;
// Main class
class Geeks {
// Main driver method
public static void main(String[] args)
{
// Creating object of Set of type String
Set<String> h = new HashSet<String>();
// Adding elements into the HashSet
// using add() method
// Custom input elements
h.add("India");
h.add("Australia");
h.add("South Africa");
// Adding the duplicate element
h.add("India");
// Displaying the HashSet
System.out.println(h);
// Removing items from HashSet
// using remove() method
h.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + h);
// Iterating over hash set items
System.out.println("Iterating over set:");
// Iterating through iterators
Iterator<String> i = h.iterator();
// It holds true till there is a single element
// remaining in the object
while (i.hasNext())
System.out.println(i.next());
}
}
Output[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India
Class 2: EnumSet
EnumSet class which is implemented in the collections framework is one of the specialized implementations of the Set interface for use with the enumeration type. It is a high-performance set implementation, much faster than HashSet. All of the elements in an enum set must come from a single enumeration type that is specified when the set is created either explicitly or implicitly. Let's see how to create a set object using this class.
Example: This example demonstrates how to create and initialize a set using EnumSet.
Java
// Java program to demonstrate the
// creation of the set object
// using the EnumSet class
import java.util.*;
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }
;
public class Geeks {
public static void main(String[] args)
{
// Creating a set
Set<Gfg> s1;
// Adding the elements
s1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.LEARN, Gfg.CODE);
System.out.println("Set 1: " + s1);
}
}
OutputSet 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Class 3: LinkedHashSet
LinkedHashSet class which is implemented in the collections framework is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. Let's see how to create a set object using this class.
Example: This example demonstrates how to use a LinkedHashSet to maintain insertion.
Java
// Java program to demonstrate the
// creation of Set object using
// the LinkedHashset class
import java.util.*;
class Geeks {
public static void main(String[] args)
{
Set<String> lh = new LinkedHashSet<String>();
// Adding elements into the LinkedHashSet
// using add()
lh.add("India");
lh.add("Australia");
lh.add("South Africa");
// Adding the duplicate
// element
lh.add("India");
// Displaying the LinkedHashSet
System.out.println(lh);
// Removing items from LinkedHashSet
// using remove()
lh.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + lh);
// Iterating over linked hash set items
System.out.println("Iterating over set:");
Iterator<String> i = lh.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
Output[India, Australia, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa
Class 4: TreeSet
TreeSet class which is implemented in the collections framework and implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can iterate in descending order using the method TreeSet.descendingIterator(). Let's see how to create a set object using this class.
Example: This example demonstrates how to use a TreeSet to store elements in a sorted order.
Java
// Java Program Demonstrating Creation of Set object
// Using the TreeSet class
// Importing utility classes
import java.util.*;
// Main class
class Geeks {
// Main driver method
public static void main(String[] args)
{
// Creating a Set object and declaring it of String
// type
// with reference to TreeSet
Set<String> ts = new TreeSet<String>();
// Adding elements into the TreeSet
// using add()
ts.add("India");
ts.add("Australia");
ts.add("South Africa");
// Adding the duplicate
// element
ts.add("India");
// Displaying the TreeSet
System.out.println(ts);
// Removing items from TreeSet
// using remove()
ts.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + ts);
// Iterating over Tree set items
System.out.println("Iterating over set:");
Iterator<String> i = ts.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
Output[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
10 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Programming BasicsJava is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easier
8 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods, or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion of memory dedicated
7 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read