Java HashSet tutorial

Java HashSet tutorial shows how to use Java HashSet collection.

Java HashSet

HashSet is a collection that contains no duplicate elements. This class offers constant time performance for the basic operations (add, remove, contains, and size). HashSet does not provide ordering of elements. HashSet does not have a get() method to retrieve elements.

HashSet implements the Set interface. The Set is a collection with no duplicates. This interface models the mathematical set abstraction.

Java HashSet constructors

E is the type of the element.

Java HashSet methods

The following table provides a few HashSet methods.

Modifier and type Method Description
void clear() Removes all elements from the set.
Object clone() Returns a shallow copy of the HashSet instance: the elements themselves are not cloned.
boolean contains(Object o) Returns true if this set contains the specified element.
boolean isEmpty() Returns true if this set is empty.
boolean add(E e) Adds the specified element to this set if it is not already present.
boolean remove(Object o) Removes the specified element from this set if it is present.
boolean removeAll(Collection<?> c) Removes from this set all of its elements that are contained in the specified collection.
Iterator<E> iterator() Returns an iterator over the elements in this set.
int size() Returns the number of elements in this set.

In this tutorial, we will work with several of these methods.

Java HashSet creation

HashSet is created with new keyword.

Set<String> brands = new HashSet<>();

The type of the element between angle brackets. Thanks to type inference, it is not necessary to provide types on the right side of the declaration.

Java HashSet adding elements

The add() method is used to add an element into the set.

brands.add("Pepsi");

The parameter is the element to be added to the set.

Java HashSet determining capacity

The size() method returns the number of elements in the set.

int nOfElements = brands.size();

Java HashSet example I

The following example creates a HashSet, determines its size, and prints all elements to the console.

HashSetSize.java
package com.zetcode;

import java.util.HashSet;
import java.util.Set;

public class HashSetSize {

    public static void main(String[] args) {
        
        Set<String> brands = new HashSet<>();
        
        brands.add("Wilson");
        brands.add("Nike");
        brands.add("Volvo");
        brands.add("IBM");
        brands.add("IBM");
        
        int nOfElements = brands.size();
        
        System.out.format("The set contains %d elements%n", nOfElements);
        System.out.println(brands);
    }
}

In the code example, we have create a HashSet of brands. Each brand must be unique. For instance, there cannot be two IBM companies registered.

brands.add("IBM");
brands.add("IBM");

Even thought we try to add a brand two times, a set contains only one IBM brand.

int nOfElements = brands.size();

We determine the size of the brands set.

System.out.println(brands);

All elements are printed to the console.

The set contains 4 elements
[Nike, Volvo, IBM, Wilson]

This is the output of the example.

Java HashSet isEmpty()

The isEmpty() method checks if the set contains any elements.

brands.isEmpty();

The parameter is the object to be removed from this set, if present.

Java HashSet removing elements

Elements from a HashSet can be deleted with remove() and removeAll() methods.

brands.remove("Pepsi");

The remove() method removes the specified element from the set if it is present.

brands.removeAll(collection);

With removeAll(), we remove all elements contained in the parameter collection from the HashSet.

Java HashSet example II

In the following example, we present add(), remove(), removeAll(), and isEmpty() methods.

HashSetRemove.java
package com.zetcode;

import java.util.HashSet;
import java.util.Set;

public class HashSetRemove {

    public static void main(String[] args) {
        
        Set<String> brands = new HashSet<>();
        
        brands.add("Wilson");
        brands.add("Nike");
        brands.add("Volvo");
        brands.add("Kia");
        brands.add("Lenovo");
        
        Set<String> brands2 = new HashSet<>();
        
        brands2.add("Wilson");
        brands2.add("Nike");
        brands2.add("Volvo");
        
        System.out.println(brands);
        
        brands.remove("Kia");
        brands.remove("Lenovo");

        System.out.println(brands);
        
        brands.removeAll(brands2);
        
        System.out.println(brands);
        
        if (brands.isEmpty()) {
        
            System.out.println("The brands set is empty");
        }        
    }
}

The example builds a HashSet of brands and removes elements from it.

System.out.println(brands);

The initial HashSet is printed to the console.

brands.remove("Kia");
brands.remove("Lenovo");

System.out.println(brands);

We remove two elements with remove() and print the contents of brands to the console.

brands.removeAll(brands2);

System.out.println(brands);

Finally, we remove all elements contained in the second set from the first set.

if (brands.isEmpty()) {

    System.out.println("The brands set is empty");
}

If the brands set is empty, we print a message to the terminal.

[Nike, Lenovo, Kia, Volvo, Wilson]
[Nike, Volvo, Wilson]
[]
The brands set is empty

This is the output of the example.

Java HashSet clear()

The clear() method deletes all elements from the set.

brands.clear();

The method has no parameters.

Java HashSet contains()

The contains() method returns true if the set contains the specified element.

brands.contains("Volvo");

The parameter is the element whose presence in this set is to be tested.

Java HashSet example III

In the following example, we use add(), contains(), clear(), and isEmpty() methods.

HashSetContains.java
package com.zetcode;

import java.util.HashSet;
import java.util.Set;

public class HashSetContains {

    public static void main(String[] args) {

        Set<String> brands = new HashSet<>();

        brands.add("Wilson");
        brands.add("Nike");
        brands.add("Volvo");
        brands.add("Kia");
        brands.add("Lenovo");

        if (brands.contains("Wilson")) {

            System.out.println("The set contains the Wilson element");
        } else {

            System.out.println("The set does not contain the Wilson element");
        }

        if (brands.contains("Apple")) {

            System.out.println("The set contains the Apple element");
        } else {

            System.out.println("The set does not contain the Apple element");
        }
        
        brands.clear();
        
        if (brands.isEmpty()) {
            
            System.out.println("The set does not contain any elements.");
        }        
        
    }
}

In the example, we check if two elements are present in the set.

if (brands.contains("Wilson")) {

    System.out.println("The set contains the Wilson element");
} else {

    System.out.println("The set does not contain the Wilson element");
}

We check if "Wilson" brand is present in the set and print a message accordingly.

The set contains the Wilson element
The set does not contain the Apple element
The set does not contain any elements.

This is the output of the example.

Java HashSet iteration with forEach()

We use Java 8 forEach() method to iterate over the elements of the HashSet. The forEach() method performs the given action for each element of the set until all elements have been processed or the action throws an exception.

HashSetForEach.java
package com.zetcode;

import java.util.HashSet;
import java.util.Set;

public class HashSetForEach {

    public static void main(String[] args) {

        Set<String> brands = new HashSet<>();

        brands.add("Wilson");
        brands.add("Nike");
        brands.add("Volvo");
        brands.add("Kia");
        brands.add("Lenovo");

        brands.forEach(e -> System.out.println(e));
    }
}

With forEach() method, we iterate over the set and print its elements to the console.

Java HashSet iteration with iterator

Iterator is an object used to iterate over a collection. The iterator is retrieved with iterator().

HashSetForEach.java
package com.zetcode;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetIterator {

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

        brands.add("Wilson");
        brands.add("Nike");
        brands.add("Volvo");
        brands.add("Kia");
        brands.add("Lenovo");

        Iterator<String> it = brands.iterator();
        
        while (it.hasNext()) {
            
            String element = it.next();
            
            System.out.println(element);
        }
    }
}

The code example iterates over all elements of HashSet and prints them to the console.

Java HashSet iteration with enhanced for loop

Enhanced for loop, introduced in Java 5, can be used to iterate over a HashSet.

HashSetEnhancedFor.java
package com.zetcode;

import java.util.HashSet;
import java.util.Set;

public class HashSetEnhancedFor {

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

        brands.add("Wilson");
        brands.add("Nike");
        brands.add("Volvo");
        brands.add("Kia");
        brands.add("Lenovo");      
        
        for (String brand: brands) {
            
            System.out.println(brand);
        }
    }
}

In the example, we iterate over a HashSet with enhanced for loop.

for (String brand: brands) {
    
    System.out.println(brand);
}

In each for cycle, a new element is assigned to the brand variable.

In this tutorial, we have presented the Java HashSet collection. You might also be interested in the related tutorials: Java HashMap tutorial, Java ArrayList tutorial, Java static keyword, HashMap iteration in Java, Java 8 forEach tutorial, Reading text files in Java, Reading and writing ICO images in Java, Java tutorial, Displaying image in Java.