Core JavaHashSet

Java HashSet Example

Photo of Ilias KoutsakisIlias KoutsakisJuly 30th, 2014Last Updated: July 30th, 2014
0 67 2 minutes read

HashSet is a Java class that extendsAbstractSet and implements theSet interface. It used to create collections by keeping an internalHashMap, but it does not permit the appearance of duplicate elements (as it is supposed to represent the mathematical “set” abstraction. We are going to take a look at how to use it and what you can accomplish through its methods.

 

 

 

1. HashSet Example

import java.util.HashSet;import java.util.Iterator;public class HashSetMain {    public static void main(String[] args) {                // Initialization of an empty HashSet,        // which will contain String objects.        HashSet set = new HashSet();                // Adding elements to the Hashset.        set.add("String 1");        set.add("String 2");        set.add("String 3");        set.add("String 4");        set.add("String 5");                // Print all the elements in the set.        System.out.println(set);                // Get the number of elements (size) of the HashSet.        System.out.println("Number of elements in the HashSet: " + set.size());                // We can also check if a specific element exists in the HashSet.        if (set.contains("String 10"))  // does not exist            System.out.println("String 10 found!");        else            System.out.println("String 10 not found!");        if (set.contains("String 3"))   // exists            System.out.println("String 3 found!");        else            System.out.println("String 3 not found!");                // We can get an iterator and manipulate all the objects        // that are contained in the HashSet.        Iterator setIterator = set.iterator();        while (setIterator.hasNext()) {            System.out.println("Iterated: " + setIterator.next());        }                // We can remove elements from the set.        set.remove("String 1");        set.remove("String 2");        System.out.println(set);                // We can remove everything from the set and empty it,        // using the clear method. We can also check if it is empty or not.        set.clear();        System.out.println("Is HashSet empty after clear(): " + set.isEmpty());    }}

Output:

[String 4, String 3, String 5, String 2, String 1]Number of elements in the HashSet: 5String 10 not found!String 3 found!Iterated: String 4Iterated: String 3Iterated: String 5Iterated: String 2Iterated: String 1[String 4, String 3, String 5]Is HashSet empty after clear(): true

Keep in mind the fact thatHashSet does not keep the order in which the elements were inserted. That’s why the iterator output is in a randomized order.

2. Method Explanation

Let’s take a look at the methods that are used in the example above.

  • add(Object obj): Add an object to the HashSet collection. If the element already exists, it will not be inserted again. It permits however to add anull value.
  • remove(Object obj): Remove an object, if it exists in the HashSet.
  • size(): Get the size (number of elements) of the HashSet.
  • contains(Object obj): Check if an object
  • clear(): Remove everything from the HashSet.
  • isEmpty(): Returnstrue if the HashSet is empty,false otherwise.
  • iterator(): Get an iterator which can be used to iterate over the contained objects.

3. Download the example

This was an example of HashSet in Java.

Download
You can download the full source code of this example here : HashSetExample
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Tags
Photo of Ilias KoutsakisIlias KoutsakisJuly 30th, 2014Last Updated: July 30th, 2014
0 67 2 minutes read
Photo of Ilias Koutsakis

Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.