codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

53 / 65 topics
50Java Collections51Java ArrayList52Java LinkedList53Java HashSet54Java HashMap55Java Iterator
Tutorials/Java Programming/Java HashSet
☕Java Programming

Java HashSet

Updated 2026-05-12
15 min read

Java HashSet

In the world of programming, managing collections of data is a common task. One such collection type is the HashSet, which is part of Java's Collections Framework. A HashSet is a collection that does not allow duplicate elements and provides constant time performance for basic operations like add, remove, and contains.

Understanding how to use a HashSet is crucial for efficient data management in your applications. In this tutorial, we'll explore the basics of HashSet, including how to create it, add elements, remove elements, check for existence, and iterate over its contents.

Introduction

A HashSet is an implementation of the Set interface that uses a hash table to store its elements. This means that operations like adding, removing, and checking for the presence of an element are generally faster compared to other collection types, especially when dealing with large datasets.

In this tutorial, we'll cover the following topics:

  • Creating a HashSet
  • Adding elements
  • Removing elements
  • Checking for existence
  • Iterating over elements

By the end of this tutorial, you'll have a solid understanding of how to use HashSet in your Java applications.

Core Content

1. Creating a HashSet

To create a HashSet, you need to import it from the java.util package and then instantiate it. Here's a simple example:

CreateHashSet.java
1import java.util.HashSet;
2
3public class CreateHashSet {
4 public static void main(String[] args) {
5 // Creating a HashSet
6 HashSet<String> set = new HashSet<>();
7
8 // Adding elements to the HashSet
9 set.add("Apple");
10 set.add("Banana");
11 set.add("Cherry");
12
13 // Printing the HashSet
14 System.out.println(set);
15 };
16}
Output
[Apple, Banana, Cherry]

2. Adding Elements

Adding elements to a HashSet is straightforward. You can use the add() method. If you try to add a duplicate element, it won't be added again because sets do not allow duplicates.

AddElements.java
1import java.util.HashSet;
2
3public class AddElements {
4 public static void main(String[] args) {
5 HashSet<String> set = new HashSet<>();
6
7 // Adding elements
8 set.add("Apple");
9 set.add("Banana");
10 set.add("Cherry");
11 set.add("Apple"); // Duplicate element
12
13 // Printing the HashSet
14 System.out.println(set);
15 }
16}
Output
[Apple, Banana, Cherry]

3. Removing Elements

To remove an element from a HashSet, you can use the remove() method. This method removes the specified element if it is present.

RemoveElements.java
1import java.util.HashSet;
2
3public class RemoveElements {
4 public static void main(String[] args) {
5 HashSet<String> set = new HashSet<>();
6
7 // Adding elements
8 set.add("Apple");
9 set.add("Banana");
10 set.add("Cherry");
11
12 // Removing an element
13 set.remove("Banana");
14
15 // Printing the HashSet
16 System.out.println(set);
17 }
18}
Output
[Apple, Cherry]

4. Checking for Existence

To check if a specific element exists in a HashSet, you can use the contains() method. This method returns true if the element is present and false otherwise.

CheckExistence.java
1import java.util.HashSet;
2
3public class CheckExistence {
4 public static void main(String[] args) {
5 HashSet<String> set = new HashSet<>();
6
7 // Adding elements
8 set.add("Apple");
9 set.add("Banana");
10 set.add("Cherry");
11
12 // Checking for existence
13 boolean containsApple = set.contains("Apple");
14 boolean containsOrange = set.contains("Orange");
15
16 // Printing the results
17 System.out.println("Contains Apple: " + containsApple);
18 System.out.println("Contains Orange: " + containsOrange);
19 }
20}
Output
Contains Apple: true
Contains Orange: false

5. Iterating Over Elements

To iterate over the elements of a HashSet, you can use an enhanced for loop or convert it to an array or list and then iterate over that.

Using Enhanced For Loop

IterateWithForLoop.java
1import java.util.HashSet;
2
3public class IterateWithForLoop {
4 public static void main(String[] args) {
5 HashSet<String> set = new HashSet<>();
6
7 // Adding elements
8 set.add("Apple");
9 set.add("Banana");
10 set.add("Cherry");
11
12 // Iterating over the HashSet using an enhanced for loop
13 for (String fruit : set) {
14 System.out.println(fruit);
15 }
16 }
17}
Output
Apple
Banana
Cherry

Using Iterator

Alternatively, you can use an iterator to iterate over the elements.

IterateWithIterator.java
1import java.util.HashSet;
2import java.util.Iterator;
3
4public class IterateWithIterator {
5 public static void main(String[] args) {
6 HashSet<String> set = new HashSet<>();
7
8 // Adding elements
9 set.add("Apple");
10 set.add("Banana");
11 set.add("Cherry");
12
13 // Iterating over the HashSet using an iterator
14 Iterator<String> iterator = set.iterator();
15 while (iterator.hasNext()) {
16 System.out.println(iterator.next());
17 }
18 }
19}
Output
Apple
Banana
Cherry

Practical Example

Let's create a practical example where we manage a collection of unique user IDs using a HashSet.

UserManagement.java
1import java.util.HashSet;
2import java.util.Scanner;
3
4public class UserManagement {
5 public static void main(String[] args) {
6 HashSet<String> userIds = new HashSet<>();
7 Scanner scanner = new Scanner(System.in);
8
9 while (true) {
10 System.out.println("Enter a user ID (or 'exit' to quit):");
11 String input = scanner.nextLine();
12
13 if (input.equalsIgnoreCase("exit")) {
14 break;
15 }
16
17 if (!userIds.contains(input)) {
18 userIds.add(input);
19 System.out.println("User ID added successfully.");
20 } else {
21 System.out.println("User ID already exists.");
22 }
23 }
24
25 System.out.println("All user IDs:");
26 for (String id : userIds) {
27 System.out.println(id);
28 }
29
30 scanner.close();
31 }
32}

Running the Practical Example

Terminal
$ javac UserManagement.java
$ java UserManagement
Enter a user ID (or 'exit' to quit):
user1
User ID added successfully.
Enter a user ID (or 'exit' to quit):
user2
User ID added successfully.
Enter a user ID (or 'exit' to quit):
user1
User ID already exists.
Enter a user ID (or 'exit' to quit):
exit
All user IDs:
user1
user2

Summary

ConceptDescription
Creating a HashSetUse new HashSet<>() to create a new instance.
Adding ElementsUse add() method to add elements. Duplicates are not allowed.
Removing ElementsUse remove() method to remove an element if it exists.
Checking ExistenceUse contains() method to check if an element is present in the set.
Iterating OverUse enhanced for loop or iterator to iterate over elements of the HashSet.

What's Next?

Now that you have a good understanding of how to use HashSet, the next topic will be Java HashMap. A HashMap is another powerful data structure in Java that allows you to store key-value pairs and provides fast access to values based on keys. We'll explore its features, usage, and differences from HashSet. Stay tuned!


PreviousJava LinkedListNext Java HashMap

Recommended Gear

Java LinkedListJava HashMap