English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java HashSet Class

In this tutorial, we will learn about the Java HashSet class. We will learn different hash set methods and operations through examples.

The Java Collections framework's HashSet class provides the functionality of the hash table data structure.

It implementsSet interface.

Create a hash set

To create a hash set, we must first import the java.util.HashSet package.

After importing the package, you can create a hash set in Java.

//with8capacity and 0.75HashSet with load factor
HashSet<Integer> numbers = new HashSet<>(8, 0.75);

Here, we create a hash set named numbers.

Note, the new part HashSet<>(8, 0.75). Here, the first parameter isCapacityand the second parameter isLoad factor.

  • capacity -The capacity of this hash set is8. This means that it can store8elements.

  • loadFactor - The load factor of this hash set is 0.6. This means that as long as our hash set is filled60%, the elements will be moved to a new hash table, which is twice the size of the original hash table.

Default capacity and load factor

It is possible to create a hash table without defining its capacity and load factor. For example,

//A HashSet with default capacity and load factor
HashSet<Integer> numbers1 = new HashSet<>();

Default,

  • The capacity of the hash set will be 16

  • The load factor will be 0.75

HashSet methods

The HashSet class provides various methods that allow us to perform various operations on the collection.

Insert element into HashSet

  • add() - Insert the specified element into the collection

  • addAll() - Insert all elements of the specified collection into the collection

For example,

import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        HashSet<Integer> evenNumber = new HashSet<>();
        // Use the add() method
        evenNumber.add(2);
        evenNumber.add(4);
        evenNumber.add(6);
        System.out.println("HashSet: " + evenNumber);
        HashSet<Integer> numbers = new HashSet<>();
        
        // Use the addAll() method
        numbers.addAll(evenNumber);
        numbers.add(5);
        System.out.println("New HashSet: " + numbers);
    }
}

Output Result

HashSet: [2, 4, 6]
New HashSet: [2, 4, 5, 6]

Access HashSet elements

To access the elements of the hash set, we can use the iterator() method. To use this method, we must import the java.util.Iterator package. For example,

import java.util.HashSet;
import java.util.Iterator;
class Main {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(6);
        System.out.println("HashSet: " + numbers);
        // Call the iterator() method
        Iterator<Integer> iterate = numbers.iterator();
        System.out.print("Use the HashSet with Iterator: ");
        //Access element
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Output Result

HashSet: [2, 5, 6]
Use the HashSet with Iterator: 2, 5, 6,

Delete element

  • remove() - Remove the specified element from the collection

  • removeAll() - Remove all elements from the collection

For example,

import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(6);
        System.out.println("HashSet: " + numbers);
        //Use the remove() method
        boolean value1 = numbers.remove(5);
        System.out.println("Value5Deleted? " + value1);
        boolean value2 = numbers.removeAll(numbers);
        System.out.println("Are all elements removed? " + value2);
    }
}

Output Result

HashSet: [2, 5, 6]
Value5Deleted? true
Are all elements removed? true

Set operation methods

Various methods of the HashSet class can also be used to perform various set operations.

Set集合并集

Union of Set

import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        To perform the intersection between two sets, we can use the retainAll() method. For example
        HashSet<Integer> evenNumbers = new HashSet<>();2);
        HashSet<Integer> evenNumbers = new HashSet<>();4);
        System.out.println("HashSet1: " + System.out.println("Intersection: "
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(3);
        System.out.println("HashSet2: " + numbers);
        //To perform the union between two sets, we can use the addAll() method. For example
        set union
        numbers.addAll(evenNumbers); + numbers);
    }
}

Output Result

HashSet1: [2, 4]
HashSet2: [1, 3]
System.out.println("Union is: "1, 2, 3, 4]

Union is: [

Intersection of Set

import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        HashSet<Integer> primeNumbers = new HashSet<>();
        primeNumbers.add(2);
        primeNumbers.add(3);
        System.out.println("HashSet1: " + primeNumbers);
        To perform the intersection between two sets, we can use the retainAll() method. For example
        HashSet<Integer> evenNumbers = new HashSet<>();2);
        HashSet<Integer> evenNumbers = new HashSet<>();4);
        System.out.println("HashSet2: " + System.out.println("Intersection: "
        //evenNumbers.add(
        intersection of the set
        evenNumbers.retainAll(primeNumbers); + System.out.println("Intersection: "
    }
}

Output Result

HashSet1: [2, 3]
HashSet2: [2, 4]
Intersection: [2]

Difference of Set

To calculate the difference between two sets, we can use the removeAll() method. For example,

import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        HashSet<Integer> primeNumbers = new HashSet<>();
        primeNumbers.add(2);
        primeNumbers.add(3);
        primeNumbers.add(5);
        System.out.println("HashSet1: " + primeNumbers);
        HashSet<Integer> oddNumbers = new HashSet<>();
        oddNumbers.add(1);
        oddNumbers.add(3);
        oddNumbers.add(5);
        System.out.println("HashSet2: " + oddNumbers);
        //HashSet1and HashSet2difference between the two sets
        primeNumbers.removeAll(oddNumbers);
        System.out.println("Difference: " + primeNumbers);
    }
}

Output Result

HashSet1: [2, 3, 5]
HashSet2: [1, 3, 5]
Difference: [2]

Subset of Set

To check if one set is a subset of another, we can use the containsAll() method. For example,

import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        System.out.println("HashSet1: " + numbers);
        HashSet<Integer> primeNumbers = new HashSet<>();
        primeNumbers.add(2);
        primeNumbers.add(3);
        System.out.println("HashSet2: " + primeNumbers);
        //Check if primeNumbers is a subset of numbers
        boolean result = numbers.containsAll(primeNumbers);
        System.out.println("HashSet2Is HashSet1is a subset?" + result);
    }
}

Output Result

HashSet1: [1, 2, 3, 4]
HashSet2: [2, 3]
HashSet2Is HashSet1Is it a subset? true

Other HashSet Methods

MethodDescription
clone()Create a copy of HashSet
contains()Search for the specified element in HashSet and return a boolean result
isEmpty()Check if HashSet is empty
size()Return the size of HashSet
clear()Remove all elements from HashSet

Why choose HashSet?

In Java, if we must access elements randomly, we usually use HashSet. This is because elements in the hash table are accessed using hashcodes.

The hashcode is a unique identifier that helps identify elements in the hash table.

HashSet cannot contain duplicate elements. Therefore, each element in the hash set has a unique hashcode.

Note: HashSet is not synchronized. That is, if multiple threads access the hash set simultaneously and one thread modifies the hash set, then it must be synchronized externally.