Java HashSet

What is HashSet in Java

In Java, HashSet is a collection class that implements the Set interface and is part of the Java Collections Framework. It stores elements in an unordered collection and does not allow duplicate values. A HashSet is widely used when you need a fast way to check if an element exists in a collection or when you need to store unique elements.

Why Use HashSet in Java?

HashSet offers several advantages:

  • Unique Elements: It ensures that no duplicate elements are stored in the collection.
  • Fast Lookup: The HashSet provides constant-time performance (O(1)) for basic operations such as add(), remove() and contains(), making it very efficient.
  • Unordered Collection: It doesn’t maintain any specific order of elements, which is useful when order doesn’t matter.

In many real-world scenarios, you may need to store unique elements such as a list of student IDs, product IDs, or any other identifiers, and HashSet is the ideal choice for such use cases.

How HashSet Works Internally

A HashSet works internally by using a HashMap. Each element added to the HashSet is stored as a key in the underlying HashMap with a constant value. This is why it provides efficient lookup operations.

Key points to understand:

  • No Duplicates: If you try to add a duplicate element, it will not be added.
  • Null Elements: A HashSet allows one null element.
  • Unordered: The elements are not stored in any specific order. If you iterate over a HashSet, the order of elements may vary each time.

Creating a HashSet

To create a HashSet in Java, you can use the following syntax:

Set<Type> set = new HashSet<>();

Where Type is the data type of the elements you want to store.

Example: Creating a HashSet of String Elements

import java.util.*;

public class HashSetExample {
public static void main(String[] args) {
// Creating a HashSet to store String elements
Set<String> set = new HashSet<>();

// Adding elements to the HashSet
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate, will not be added

// Printing the HashSet
System.out.println("HashSet: " + set);
}
}

Output:

HashSet: [Banana, Apple, Cherry]

In this example, even though we added “Apple” twice, it only appears once in the set, as duplicates are not allowed.

Common Operations with HashSet

Here are some of the most commonly used methods of the HashSet class:

  1. add(E e): Adds an element to the set. Returns true if the element was added successfully and false if it was already present.
  2. remove(Object o): Removes the specified element from the set.
  3. contains(Object o): Checks if the set contains the specified element.
  4. size(): Returns the number of elements in the set.
  5. clear(): Removes all elements from the set.
  6. isEmpty(): Returns true if the set is empty.

Example: Using HashSet Methods

import java.util.*;

public class HashSetOperations {
public static void main(String[] args) {
Set<String> set = new HashSet<>();

// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");

// Checking if an element exists
boolean containsApple = set.contains("Apple");
System.out.println("Contains Apple? " + containsApple);

// Removing an element
set.remove("Banana");
System.out.println("HashSet after removal: " + set);

// Checking size
System.out.println("Size of HashSet: " + set.size());

// Clearing the HashSet
set.clear();
System.out.println("HashSet after clear: " + set);
}
}

Output:

Contains Apple? true
HashSet after removal: [Apple, Cherry]
Size of HashSet: 2
HashSet after clear: []

Iterating Over a HashSet

You can iterate over a HashSet using different approaches:

  • For-each loop: A simple and efficient way to loop through the elements.
  • Iterator: Provides more control over the iteration process.
  • forEach() method (Java 8): A more functional approach introduced in Java 8.

Example: Iterating Over a HashSet

import java.util.*;

public class IterateHashSet {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");

// Iterating using a for-each loop
for (String element : set) {
System.out.println(element);
}

// Iterating using forEach() method (Java 8)
set.forEach(element -> System.out.println(element));
}
}

Output:

Apple
Banana
Cherry
Apple
Banana
Cherry

Since HashSet does not maintain any specific order, the order of the elements in the output may vary each time.

HashSet vs TreeSet vs LinkedHashSet

  • HashSet: Stores elements in an unordered way. Provides fast access with O(1) time complexity for most operations.
  • TreeSet: Stores elements in a sorted order. It implements the NavigableSet interface, which allows you to perform range operations and provides logarithmic time complexity (O(log n)) for basic operations.
  • LinkedHashSet: Maintains the insertion order of elements. It is a combination of HashSet and LinkedList, allowing for predictable iteration order while maintaining constant-time performance for most operations.

Leave a Comment