Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, a Set is a collection that contains no duplicate elements. It models the mathematical set abstraction and is used to store unique elements. The Set interface is part of the java.util package and extends the Collection interface. It is an unordered collection, which means it does not guarantee any specific order of the elements. The Set interface is implemented by various classes like HashSet, LinkedHashSet, and TreeSet.
In this article, we will discuss the Set interface in Java, its methods, and how to create Set objects & perform various operations on them.
Creating Set Objects
To create a Set object in Java, you can use one of the classes that implement the Set interface, such as HashSet, LinkedHashSet, or TreeSet. Let’s see how you can create Set objects using these classes:
1. HashSet
HashSet is the most commonly used implementation of the Set interface. It stores elements using a hash table, providing constant-time performance for basic operations like add, remove, contains & size.
Example:
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
2. LinkedHashSet
LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked list across all elements. It provides insertion-order iteration, which means the elements are returned in the order they were inserted.
Example:
Set<Integer> set = new LinkedHashSet<>();
set.add(10);
set.add(20);
set.add(30);
3. TreeSet
TreeSet is an implementation of the SortedSet interface that stores elements in a sorted order. It uses a Red-Black tree data structure to maintain the elements in a sorted manner.
Example:
Set<String> set = new TreeSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
In the above examples, we create Set objects using different implementations & add elements to them using the `add()` method.
How to use Set?
Sets are used to store unique elements in a collection. Let’s discuss some common operations you can perform on a Set:
1. Adding Elements
You can add elements to a Set using the `add()` method. If the element is already present in the Set, it will not be added again.
Example:
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // This will not be added
2. Removing Elements
To remove an element from a Set, you can use the `remove()` method. It removes the specified element from the Set if it is present.
Example:
Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.remove(10);
3. Checking for Existence
You can check if an element exists in a Set using the `contains()` method. It returns `true` if the element is present in the Set, otherwise `false`.
Example:
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
boolean contains = set.contains("Apple"); // returns true
4. Iterating over Elements
You can iterate over the elements of a Set using a for-each loop or an iterator.
Example using for-each loop:
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
for (String element : set) {
System.out.println(element);
}
}
}
You can also try this code with Online Java Compiler
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
System.out.println(element);
}
}
}
You can also try this code with Online Java Compiler
Adds the specified element to the set if it is not already present
remove(Object o)
Removes the specified element from the set if it is present
contains(Object o)
Returns true if the set contains the specified element
isEmpty()
Returns true if the set contains no elements
size()
Returns the number of elements in the set
clear()
Removes all elements from the set
iterator()
Returns an iterator over the elements in the set
toArray()
Returns an array containing all the elements in the set
toArray(T[] a)
Returns an array containing all the elements in the set, using the provided array as the storage
containsAll(Collection<?> c)
Returns true if the set contains all the elements in the specified collection
addAll(Collection<? extends E> c)
Adds all the elements in the specified collection to the set if they're not already present
retainAll(Collection<?> c)
Retains only the elements in the set that are contained in the specified collection
removeAll(Collection<?> c)
Removes from the set all of its elements that are contained in the specified collection
Illustration
Let's take a look at an example that proper use of the Set interface and its methods:
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
// Creating a Set
Set<String> fruits = new HashSet<>();
// Adding elements to the Set
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Printing the Set
System.out.println("Fruits Set: " + fruits);
// Checking if an element exists
boolean containsApple = fruits.contains("Apple");
System.out.println("Contains Apple? " + containsApple);
// Removing an element
fruits.remove("Banana");
System.out.println("Fruits Set after removing Banana: " + fruits);
// Iterating over the Set
System.out.println("Iterating over the Set:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Clearing the Set
fruits.clear();
System.out.println("Fruits Set after clearing: " + fruits);
}
}
You can also try this code with Online Java Compiler
Fruits Set: [Apple, Orange, Mango, Banana]
Contains Apple? true
Fruits Set after removing Banana: [Apple, Orange, Mango]
Iterating over the Set:
Apple
Orange
Mango
Fruits Set after clearing: []
In this example, we create a HashSet called `fruits` to store strings. We add elements to the set using the `add()` method. We then print the set, which shows that the elements are stored in an unordered manner.
We check if the set contains the element "Apple" using the `contains()` method, which returns `true`. We remove the element "Banana" using the `remove()` method & print the updated set.
We iterate over the elements of the set using a for-each loop & print each fruit.
Finally, we clear the set using the `clear()` method, which removes all elements from the set.
Performing Various Operations on SortedSet:
The SortedSet interface extends the Set interface & provides additional methods for working with sorted sets. It maintains the elements in ascending order based on their natural ordering or a specified comparator.
Let’s discuss some common operations you can perform on a SortedSet:
1. Creating a SortedSet
To create a SortedSet, you can use the TreeSet class, which implements the SortedSet interface.
Example:
SortedSet<Integer> sortedSet = new TreeSet<>();
2. Adding Elements
You can add elements to a SortedSet using the `add()` method. The elements will be inserted in the correct position based on their natural ordering or the specified comparator.
YoExu can remove elements from a SortedSet using the `remove()` method.
Example:
sortedSet.remove(10);
Hierarchy of Java Collections
The Java Collections framework provides a hierarchical structure of interfaces & classes for organizing & manipulating groups of objects. Here's an overview of the hierarchy:
The `Collection` interface is at the top of the hierarchy and defines the basic operations common to all collections, such as adding, removing, and querying elements.
The `Set` interface extends `Collection` and represents an unordered collection of unique elements. It is implemented by classes like `HashSet`, `LinkedHashSet`, and `TreeSet`.
The `SortedSet` interface extends `Set` and provides additional methods for working with sorted sets. It is implemented by the `TreeSet` class.
The `List` interface extends `Collection` and represents an ordered collection of elements that allows duplicate values. It is implemented by classes like `ArrayList`, `LinkedList`, and `Vector`.
The `Queue` interface extends `Collection` and represents a collection designed for holding elements prior to processing. It is implemented by classes like `LinkedList` and `PriorityQueue`.
The `Deque` interface (not shown in the diagram) extends `Queue` and represents a double-ended queue, allowing insertion and removal at both ends. It is implemented by classes like `ArrayDeque` and `LinkedList`.
The `Map` interface (not shown in the diagram) is part of the Collections framework but does not extend `Collection`. It represents a collection of key-value pairs and is implemented by classes like `HashMap`, `LinkedHashMap`, and `TreeMap`.
Operations on the Set Interface
The Set interface provides several operations that allow you to manipulate & query the elements in a set. Some commonly used operations are:
1. Adding Elements
- `add(E element)`: Adds the specified element to the set if it is not already present. Returns true if the set did not already contain the element.
- `addAll(Collection<? extends E> c)`: Adds all the elements in the specified collection to the set if they're not already present.
2. Removing Elements
- `remove(Object o)`: Removes the specified element from the set if it is present. Returns true if the set contained the element.
- `removeAll(Collection<?> c)`: Removes from the set all of its elements that are contained in the specified collection.
- `retainAll(Collection<?> c)`: Retains only the elements in the set that are contained in the specified collection.
- `clear()`: Removes all elements from the set.
3. Querying Elements
- `contains(Object o)`: Returns true if the set contains the specified element.
- `containsAll(Collection<?> c)`: Returns true if the set contains all the elements in the specified collection.
- `isEmpty()`: Returns true if the set contains no elements.
- `size()`: Returns the number of elements in the set.
4. Iterating Elements
- `iterator()`: Returns an iterator over the elements in the set. The elements are returned in no particular order.
5. Converting to Array
- `toArray()`: Returns an array containing all the elements in the set.
- `toArray(T[] a)`: Returns an array containing all the elements in the set, using the provided array as the storage.
These operations provide a powerful set of tools for working with sets in Java. You can add and remove elements, check for existence, query the size, iterate over the elements, and convert the set to an array.
For example :
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println("Set: " + fruits);
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);
boolean containsApple = fruits.contains("Apple");
System.out.println("Contains Apple? " + containsApple);
int size = fruits.size();
System.out.println("Size of the set: " + size);
System.out.println("Iterating over the set:");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
You can also try this code with Online Java Compiler
Set: [Apple, Orange, Banana]
After removing Banana: [Apple, Orange]
Contains Apple? true
Size of the set: 2
Iterating over the set:
Apple
Orange
Frequently Asked Questions
What is the difference between HashSet & TreeSet?
HashSet stores elements using a hash table, providing constant-time performance for basic operations, while TreeSet stores elements in a sorted order using a Red-Black tree, allowing for efficient insertion, deletion & retrieval of elements in logarithmic time.
Can a Set contain duplicate elements?
No, a Set is a collection that does not allow duplicate elements. If you attempt to add an element that already exists in the Set, the operation will be ignored & the Set will remain unchanged.
Is the Set interface thread-safe?
The Set interface itself is not thread-safe. However, you can obtain a thread-safe Set by using the `Collections.synchronizedSet()` method or by using thread-safe implementations like `ConcurrentSkipListSet`.
Conclusion
In this article, we discussed the Set interface in Java, which represents an unordered collection of unique elements. We learned how to create Set objects using different implementations like HashSet, LinkedHashSet, and TreeSet. We also looked into the various methods provided by the Set interface for adding, removing, querying, and iterating over elements. Lastly, we explained the hierarchy of Java Collections and the commonly used operations on the Set interface.