What is a HashSet in Java?

What is a HashSet?

A HashSet is a part of the Java Collections Framework that implements the Set interface, which stores unique elements and does not maintain any order of insertion.

A HashSet is perfect when you want no duplicates and to quickly find elements.

Features of HashSet in Java

HashSet offers several advantages:

  • Unique Elements: HashSet automatically removes duplicates. If you try to add a value that already exists, it will not be added again.
  • Fast Performance: HashSet provides constant-time (O(1)) performance for common operations like add(), remove(), and contains() because it uses hashing internally.
  • Unordered Collection: Elements are stored in no particular order. The order you add elements is not guaranteed to be preserved.
  • Allows Null Values: A HashSet can store one null element, but no more than one; this means duplicates are not allowed.

How HashSet Works in Java?

A HashSet in Java stores unique elements using an underlying HashMap. Each element you add becomes a key in the HashMap, which is why lookups are very fast.

Important 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 do not maintain insertion order. Iterating multiple times may show elements in a different order.

How To Create a HashSet?

Syntax of the HashSet:

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

You can see that the Type is the data type of the elements you want to store.

Example: Creating a HashSet of String Elements

import java.util.*;

public class HashSetDemo {
public static void main(String[] args) {
// Create a HashSet for storing String elements
Set<String> fruits = new HashSet<>();

// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Apple"); // Duplicate, won't be added

// Displaying the HashSet
System.out.println("Fruits in HashSet: " + fruits);
}
}

Output:

Fruits in HashSet: [Banana, Apple, Cherry]

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 and 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 HashSetDemo {
public static void main(String[] args) {
// Create a HashSet of strings
Set<String> fruits = new HashSet<>();

// Add elements to the HashSet
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Check if an element exists
System.out.println("Contains Apple? " + fruits.contains("Apple"));

// Remove an element
fruits.remove("Banana");
System.out.println("After removal: " + fruits);

// Check the size of the HashSet
System.out.println("Total elements: " + fruits.size());

// Clear all elements
fruits.clear();
System.out.println("After clearing: " + fruits);
}
}

Output:

Contains Apple? true
After removal: [Apple, Cherry]
Total elements: 2
After clearing: []

Iterating Over a HashSet

A HashSet stores unique elements without maintaining any specific order.

  • For-each loop: It is a simple way to loop through the elements.
  • Iterator: It gives more control, such as removing elements while iterating.
  • forEach() method (Java 8): A modern, functional-style approach to process each element.

Example: Iterating Over a HashSet

import java.util.*;

public class HashSetIterationDemo {
public static void main(String[] args) {
// Create a HashSet of strings
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

System.out.println("Using for-each loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}

System.out.println("\nUsing forEach() method:");
fruits.forEach(fruit -> System.out.println(fruit));
}
}

Output:

Using for-each loop:
Apple
Banana
Cherry

Using forEach() method:
Apple
Banana
Cherry

Also Learn Important Topics of Java

Leave a Comment