In this tutorial, we will explore the HashSet
class in Java, which is a specialized implementation of the Set
interface. The HashSet
class provides the basic operations for a set, including adding, removing, and iterating over elements, while ensuring that there are no duplicate elements. This tutorial will demonstrate how to use HashSet
with examples, covering all important operations and different ways for iteration using Java 8 features.
Table of Contents
- Introduction
- Prerequisites
- Step-by-Step Guide
- Creating a HashSet
- Adding and Retrieving Elements
- Iterating Over the Set
- Removing Elements
- HashSet Methods
- Complete Code Example
- Conclusion
Introduction
HashSet
is a part of Java's java.util
package and implements the Set
interface. It is backed by a HashMap
, ensuring that the elements in the set are unique and unordered. HashSet
is useful in scenarios where you need to store unique elements and do not care about the order of elements.
Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed (latest version preferred)
- An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse
Step-by-Step Guide
Step 1: Creating a HashSet
First, let's create a HashSet
and add some elements to it.
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Print the set
System.out.println("HashSet: " + hashSet);
}
}
Output:
HashSet: [Arjun, Lakshmi, Ravi, Sita]
Step 2: Adding and Retrieving Elements
Let's add some elements to the HashSet
and check if certain elements are present.
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Check if elements are present
System.out.println("Contains Ravi: " + hashSet.contains("Ravi"));
System.out.println("Contains Gopal: " + hashSet.contains("Gopal"));
}
}
Output:
Contains Ravi: true
Contains Gopal: false
Step 3: Iterating Over the Set
We can iterate over the HashSet
using a for-each loop, iterator, and Java 8 features like forEach and streams.
Using For-Each Loop
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Iterate over the set using for-each loop
System.out.println("Iterating over HashSet using for-each loop:");
for (String element : hashSet) {
System.out.println(element);
}
}
}
Output:
Iterating over HashSet using for-each loop:
Arjun
Lakshmi
Ravi
Sita
Using Iterator
import java.util.Iterator;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Iterate over the set using iterator
System.out.println("Iterating over HashSet using iterator:");
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
Iterating over HashSet using iterator:
Arjun
Lakshmi
Ravi
Sita
Using forEach and Lambda Expression (Java 8)
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Iterate over the set using forEach and lambda
System.out.println("Iterating over HashSet using forEach and lambda:");
hashSet.forEach(element -> System.out.println(element));
}
}
Output:
Iterating over HashSet using forEach and lambda:
Arjun
Lakshmi
Ravi
Sita
Using Streams (Java 8)
import java.util.stream.Collectors;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Iterate over the set using streams
System.out.println("Iterating over HashSet using streams:");
hashSet.stream().forEach(System.out::println);
// Convert HashSet to a List using streams
System.out.println("HashSet to List:");
hashSet.stream().collect(Collectors.toList()).forEach(System.out::println);
}
}
Output:
Iterating over HashSet using streams:
Arjun
Lakshmi
Ravi
Sita
HashSet to List:
Arjun
Lakshmi
Ravi
Sita
Step 4: Removing Elements
Let's remove elements from the HashSet
and demonstrate the use of the remove
method.
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Remove an element
hashSet.remove("Arjun");
// Print the set after removal
System.out.println("HashSet after removal: " + hashSet);
}
}
Output:
HashSet after removal: [Lakshmi, Ravi, Sita]
Step 5: HashSet Methods
Here are some other important methods provided by the HashSet
class:
addAll(Collection<? extends E> c)
: Adds all of the elements in the specified collection to this set.clear()
: Removes all of the elements from this set.isEmpty()
: Returnstrue
if this set contains no elements.size()
: Returns the number of elements in this set.
import java.util.HashSet;
import java.util.Set;
public class HashSetMethodsExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Use addAll method
Set<String> anotherSet = new HashSet<>();
anotherSet.add("Ram");
anotherSet.add("Shyam");
hashSet.addAll(anotherSet);
System.out.println("After addAll: " + hashSet);
// Check if the set is empty
System.out.println("Is HashSet empty? " + hashSet.isEmpty());
// Get the size of the set
System.out.println("Size of HashSet: " + hashSet.size());
// Clear the set
hashSet.clear();
System.out.println("After clear: " + hashSet);
}
}
Output:
After addAll: [Arjun, Ram, Shyam, Lakshmi, Ravi, Sita]
Is HashSet empty? false
Size of HashSet: 6
After clear: []
Complete Code Example
Here's the complete code example demonstrating various operations with HashSet
:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();
// Add elements to the set
hashSet.add("Ravi");
hashSet.add("Sita");
hashSet.add("Arjun");
hashSet.add("Lakshmi");
// Check if elements are present
System.out
.println("Contains Ravi: " + hashSet.contains("Ravi"));
System.out.println("Contains Gopal: " + hashSet.contains("Gopal"));
// Iterate over the set using for-each loop
System.out.println("Iterating over HashSet using for-each loop:");
for (String element : hashSet) {
System.out.println(element);
}
// Iterate over the set using iterator
System.out.println("Iterating over HashSet using iterator:");
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Iterate over the set using forEach and lambda
System.out.println("Iterating over HashSet using forEach and lambda:");
hashSet.forEach(element -> System.out.println(element));
// Iterate over the set using streams
System.out.println("Iterating over HashSet using streams:");
hashSet.stream().forEach(System.out::println);
// Convert HashSet to a List using streams
System.out.println("HashSet to List:");
hashSet.stream().collect(Collectors.toList()).forEach(System.out::println);
// Remove an element
hashSet.remove("Arjun");
System.out.println("HashSet after removal: " + hashSet);
// Use addAll method
Set<String> anotherSet = new HashSet<>();
anotherSet.add("Ram");
anotherSet.add("Shyam");
hashSet.addAll(anotherSet);
System.out.println("After addAll: " + hashSet);
// Check if the set is empty
System.out.println("Is HashSet empty? " + hashSet.isEmpty());
// Get the size of the set
System.out.println("Size of HashSet: " + hashSet.size());
// Clear the set
hashSet.clear();
System.out.println("After clear: " + hashSet);
}
}
Output:
Contains Ravi: true
Contains Gopal: false
Iterating over HashSet using for-each loop:
Arjun
Lakshmi
Ravi
Sita
Iterating over HashSet using iterator:
Arjun
Lakshmi
Ravi
Sita
Iterating over HashSet using forEach and lambda:
Arjun
Lakshmi
Ravi
Sita
Iterating over HashSet using streams:
Arjun
Lakshmi
Ravi
Sita
HashSet to List:
Arjun
Lakshmi
Ravi
Sita
HashSet after removal: [Lakshmi, Ravi, Sita]
After addAll: [Arjun, Ram, Shyam, Lakshmi, Ravi, Sita]
Is HashSet empty? false
Size of HashSet: 6
After clear: []
Conclusion
In this tutorial, we demonstrated how to use the HashSet
class in Java. We covered creating a HashSet
, adding and retrieving elements, iterating over the set using various methods, removing elements, and using some important HashSet
methods. By following this guide, developers can effectively use HashSet
in scenarios where the uniqueness of elements is important.
Comments
Post a Comment
Leave Comment