For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 10 AM to 7 PM
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
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!
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.
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.
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
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);
}
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.
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);
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);
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
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.
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);
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();
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);
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);
}
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.
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();
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.
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.
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.
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.
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.
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.
-9cd0a42cab014b9e8d6d4c4ba3f27ab1.webp&w=3840&q=75)
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free

Author|907 articles published
Recommended Programs