Set in Java: Operations, Examples & Uses

Updated on 02/09/20255,312 Views

Java provides a variety of data structures for managing collections, and Set in Java is one of the most fundamental. A Set is an unordered collection that allows only unique elements, making it ideal for situations where duplicates are not allowed. It differs from lists or arrays by automatically enforcing uniqueness and offering operations like union, intersection, and difference. 

In this tutorial, we will explore Set in Java in detail. You will learn about its key implementations, including HashSet, TreeSet, and LinkedHashSet. We will also cover essential operations such as adding, removing, iterating, and performing set-specific methods with practical code examples to help you master sets in your Java applications. 

Looking to advance your Java skills? Check out upGrad’s Online Software Engineering Courses. Start today to strengthen your foundation and accelerate your career growth by learning JavaScript, Node.js, APIs, React, and more! 

What Is a Set in Java? 

A Set in Java is a collection that stores unique elements and does not allow duplicates. Unlike Lists, Sets do not maintain any specific order of elements, though some implementations like TreeSet or LinkedHashSet provide sorted or insertion-order preservation.  

Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand. 

  • Professional Certificate Program in Cloud Computing and DevOps
  • AI-Powered Full Stack Development Course by IIITB
  • Future-Proof Your Tech Career with AI-Driven Full-Stack Development

Sets are widely used when uniqueness is important, such as storing IDs, names, or other distinct items. Java provides multiple Set implementations, including HashSet, TreeSet, and LinkedHashSet, each with its characteristics and performance benefits. By using a Set in Java, developers can efficiently add, remove, and search elements while ensuring no duplicates exist in the collection.

Creating Set Objects

Any of the Set executions that are accessible, like HashSet, TreeSet, or LinkedHashSet, can be utilized to fabricate a Set object in Java. With code bits, pictures, and visuals, we should analyze every one of these implementations.

HashSet: The most often used implementation of the Set interface is HashSet in Java. It offers constant-time performance for fundamental operations like adding, deleting, or verifying for element existence but does not guarantee the order of the items. Here is an illustration of how to build a HashSet and add components to it:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange");  

TreeSet in Java: The SortedSet interface is implemented by TreeSet, which offers items in sorted order. It maintains the elements in ascending order, which makes it suitable for scenarios where you require sorted data. Here's an example of creating a TreeSet and adding elements to it:

java
Set<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8);  

LinkedHashSet: Execution of the Set connection point that safeguards the addition request of components is LinkedHashSet.It combines the properties of both HashSet and LinkedList, providing uniqueness and maintaining the order of insertion. Here's an example of creating a LinkedHashSet and adding elements to it:

java
Set<Character> set = new LinkedHashSet<>(); 
set.add('A'); 
set.add('B'); 
set.add('C');  

Must Read: A Complete Guide to Generics in Java with Examples and Use Cases

What Are the Operations You Can Perform on Set in Java?

A Set object can be subjected to a variety of procedures after being formed. How about we look at the ordinary activities that the Java Set.

Adding Components: You might utilize the add() capability to add components to a Set. If the mentioned component isn't now present in the Set, it is added. Here is a delineation:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange");  

Accessing the Elements: You cannot access items by their index in sets since they don't save a specific request. To get to every component independently, you might go through the Set utilizing an iterator or reach out for a circle. Here is an outline:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange"); 
 
for (String element: set) { 
    System.out.println(element); 
}  

Removing Values: The remove() function might be utilized to erase a component from a Set. Assuming the mentioned component is available in the Set, it is eliminated. Here is a representation:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange"); 
 
set.remove("Banana");  

Iterating through the Set: As recently referenced, you can utilize an iterator or stretch out for a circle to explore the Set and connect with its parts. Here is a model:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
set.add("Orange"); 
 
Iterator<String> iterator = set.iterator(); 
while (iterator.hasNext()) { 
    String element = iterator.next(); 
    System.out.println(element); 
}

Operations on the Set Interface

The Set interface provides several methods to perform operations on Sets. Let's explore some of the commonly used methods with code examples, screenshots, and images.

  • Intersection

The retainAll() method allows you to perform the intersection operation on two Sets. Just the things that are likewise present in the given Set are kept as a component of the change to the ongoing Set. Here is a representation:

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
set1.add("Orange"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Banana"); 
set2.add("Orange"); 
set2.add("Mango"); 
 
set1.retainAll(set2);  

  • Union

You may combine two Sets using the union operation by using the addAll() function. It adds each component from the picked Set to the one that is, as of now, there.

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
set1.add("Orange"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Banana"); 
set2.add("Orange"); 
set2.add("Mango"); 
 
set1.addAll(set2);  
  • Difference

The removeAll() technique permits you to play out the distinction procedure on two Sets. It eliminates every one of the components present in the predetermined Set from the ongoing Set.

java 
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
set1.add("Orange"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Banana"); 
set2.add("Orange"); 
set2.add("Mango"); 
 
set1.removeAll(set2);  

Also Read: Packages in Java Programming – Concepts and Examples

Performing Various Operations on SortedSet

The Set interface is extended by the SortedSet interface, which offers more actions for sorted sets. Let's examine a few of these procedures and how to carry them out using screenshots, code samples, and visuals.

  • Adding Elements

The add() method is used to add elements to a SortedSet. It maintains the elements in sorted order based on their natural ordering or a custom Comparator.

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8);  
  • Accessing the Elements

You can access the elements in a SortedSet using iteration or specific methods such as first() and last().

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8); 
 
int firstElement = set.first(); 
int lastElement = set.last();  
  • Removing the Values

The remove() method is utilized to eliminate a component from a SortedSet. It eliminates the predetermined component assuming it exists in the set.

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8); 
 
set.remove(2);  
  • Iterating through the Set

You can traverse over a SortedSet using an Iterator or an improved for loop, just like you do with other Set implementations.

java
SortedSet<Integer> set = new TreeSet<>(); 
set.add(5); 
set.add(2); 
set.add(8); 
 
Iterator<Integer> iterator = set.iterator(); 
while (iterator.hasNext()) { 
    int element = iterator.next(); 
    System.out.println(element); 
}

Description

Sets in Java are powerful tools for managing collections of unique elements. They provide methods for adding, accessing, removing, and iterating over elements. Sets also support set operations like intersection, union, and difference through the Set interface. The SortedSet interface extends the Set interface and adds sorting capabilities to the sets.

Set Methods

The Set interface provides various methods to perform operations on Sets. Let's quickly go over a few of these techniques using screenshots, code samples, and visuals.

add():

This method adds an element to the Set if it is not already present.

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana");  

addAll():

This method adds all the elements from another collection to the Set.

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.addAll(set1);  

clear():

This method removes all the elements from the Set, making it empty.

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
set.clear();  

contains():

This method checks whether the Set contains a specific element.

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
boolean containsApple = set.contains("Apple");  

containsAll():

This method checks whether the Set contains all the elements from another collection.

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Apple"); 
 
boolean containsAll = set1.containsAll(set2);  

hashCode():

This method returns the hash code value of the Set.

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
int hashCode = set.hashCode();  

isEmpty():

This method checks whether the Set is empty.

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
boolean isEmpty = set.isEmpty();  

iterator():

This method returns an iterator over the elements in the Set. Here's an example:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
Iterator<String> iterator = set.iterator(); 
while (iterator.hasNext()) { 
    String element = iterator.next(); 
    System.out.println(element); 
}  

remove():

This method removes a specific element from the Set if it exists. Here's an example:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
set.remove("Apple");  

removeAll():

This method removes all the elements from the Set that are present in another collection. Here's an example:

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Apple"); 
 
set1.removeAll(set2);  

retainAll():

This strategy holds just the components from the Set that are available in another assortment, successfully playing out the crossing point activity. Here is a model:

java
Set<String> set1 = new HashSet<>(); 
set1.add("Apple"); 
set1.add("Banana"); 
 
Set<String> set2 = new HashSet<>(); 
set2.add("Apple"); 
 
set1.retainAll(set2);  

size():

This method returns the number of elements in the Set. Here's an example:

java
Set<String> set = new HashSet<>(); 
set.add("Apple"); 
set.add("Banana"); 
 
int size = set.size();  

Conclusion

In conclusion, a Set in Java is a powerful data structure for managing collections of unique elements. This tutorial covered the concept of Sets, their key implementations like HashSet, TreeSet, and LinkedHashSet, and the common operations such as adding, removing, iterating, and performing set operations like union, intersection, and difference.  

Understanding Sets helps you efficiently organize and manipulate data without duplicates. By mastering the Set in Java and its operations, you can write cleaner, more reliable code and effectively handle scenarios requiring uniqueness, sorted data, or insertion-order preservation in your Java applications.

FAQs

1. What is a Set in Java, and how does it differ from other collection classes?

A Set in Java is a collection that does not allow duplicate elements. Classes like HashSet, TreeSet, and LinkedHashSet are examples of those that implement it. Unlike a List and a Map, a Set does not keep a particular order for the components. It ensures that each element appears only once in the collection, making it the perfect solution for situations where uniqueness is a crucial necessity.

2. In Java, how can I add elements to a Set?

The add() function of the Set interface may be used to add elements to a Set. For example, you might add parts to a HashSet named "mySet" by utilizing mySet.add(element). The add() capability will return misleading, demonstrating that the component was not added, assuming the component is, as of now, present in the Set.

3. Could I, at any point, get parts out of a set in a specific request?

No, Sets do not ensure that the components will appear in a certain order, unlike List or Map. Utilize a SortedSet execution like TreeSet to hold components in arranged requests if you want to get to them in a predetermined request.

4. How might I decide if a component is essential for a Set?

The incorporates() strategy for the Set connection point in Java might be utilized to decide if a component is available in a Set. Assuming the component is situated in the Set, it returns valid; in any case, it gets back bogus.

5. Can I modify elements in a Set directly?

No, the Set interface does not provide any methods to modify individual elements directly. To modify an element in a Set, you need to remove the old element and add the modified element as a separate operation.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow

FREE COURSES

Start Learning For Free

image
Pavan Vadapalli

Author|911 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

Top Resources

Recommended Programs

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 10 AM to 7 PM

text

Indian Nationals

text

Foreign Nationals