Java HashSet: What It Is, When and How To Use It?

In this blog post we will first cover what is a Java HashSet, when to use a HashSet and show you how to use a HashSet in Java by providing several examples.

You’ll also find answers to the following questions:

  • Is HashSet ordered?
  • Is HashSet synchronized?

What is Java HashSet?

Java HashSet is a collection that implements from the Set interface. It is different from the List interface (ArrayList and LinkedList) as HashSet doesn’t keep the order of the inserted objects. For example, when you iterate over a HashSet then first inserted object might be on the second index and second inserted object might be on the first place. You never know! In addition, HashSet doesn’t have the support to access objects directly by their index like ArrayList has. To find an object in a HashSet, in the worst case scenario, it has to go through all the inserted objects.

Fun fact: HashSet in Java is actually implemented on top of HashMap. This is copied from the HashSet class:

 /**
 * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
 * default initial capacity (16) and load factor (0.75).
 */
public HashSet() {
    map = new HashMap<>();
}

In addition, HashSet doesn’t allow duplicates. To achieve that, it checks the hashcodes of the objects. When objects have the same hashcode they are also compared by their equals method. Now, if the set already contains the element, the set is left unchanged. In other words, the object you are trying to put into the set will be ignored.

The add method is described in the documentation as:java hashset add

To point out, HashSet is not synchronized. In case there are multiple threads reading from/writing to the HashSet, you might get some unexpected results.

When to use HashSet?

Java HashSet fits great when you don’t want to have duplicate objects in a collection. In other words, if you need to make sure that all the objects in a set are unique. Therefore, when using HashSet, you don’t have to have an if statement in the code to make sure that the object doesn’t already exist in the set. Let the HashSet take care of that! Just be sure to override the equals() and hashCode() methods. IDEs do a very good job auto-generating these methods for you.

How to use HashSet in Java?

HashSet in Java is simple to use. Now, lets take a look at some examples of how to create a HashSet and show some possible usages of it.

To start with, lets create an empty HashSet and populate it with some letters. We can then print out all of the letters in it.

// Creating an empty set of letters
Set<String> letters = new HashSet<>();
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");


// Display all letters
for (String letter : letters) {
    System.out.println(letter);
}

// Display all letters in the set Java 8 way
letters.forEach(letter -> System.out.println(letter));

The output of both (for-each and java8 approach) is the following:

B
A
C
E
D

Lets also print out the size of the set:

// Display how many letters we have in the set
System.out.println("Number of letters in the set: " + letters.size());

The output:

Number of letters in the set: 5

We can also create a new HashSet otherLetters out of another collection and add these letters to our already existing letters HashSet:

// Create new set by populating it with a list of letters
Set<String> otherLetters = new HashSet<>(
        Arrays.asList("X", "Y")
);

// Add the otherLetters set to the letters set and display it
letters.addAll(otherLetters);
letters.forEach(letter -> System.out.println(letter));

The output:

C
Y
B
A
X
D
E

As you remember then HashSet doesn’t allow duplicates. Lets see this in action:

// Trying to add letter X that already exists in the set.
// Should return false because HashSet ignores duplicates
System.out.println("Added letter X: " + letters.add("X"));

The output:

Added letter X: false

As a final example lets remove the letter X from the set:

// Check if set contains letter X
System.out.println(
        "(Before remove) Set contains X: " + letters.contains("X")
);

letters.remove("X");

// Check if set contains letter X
System.out.println(
        "(After remove) Set contains X: " + letters.contains("X")
);

The output:

(Before remove) Set contains X: true
(After remove) Set contains X: false

Conclusion

Java HashSet is a collection that implements from the Set interface. HashSet doesn’t keep the order of the inserted objects, ignores duplicate objects and is not synchronized. It could be used if you need to make sure that all the objects in a collection are unique. Just remember to use the equals() and hashCode() methods correctly.

Feel free to leave comments if you have any questions or feedback to give!

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *