HashSet basics

The HashSet class is a general set class that implements the Set interface. The elements are stored in a hash table that allows quick access.

It is generally used when no mapping of keys to pairs of values is required, unlike the HashMap.

Syntax

import java.util.HashSet;

HashSet<String> hashSet = new HashSet<String>();

HashSet Example

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

class HashSet {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<String>();
		set.add("First");
		set.add("Second");
		set.add("Third");
		set.add("Fourth");

		boolean isEmpty = set.isEmpty();
		int size = set.size();
		boolean containsEntry = set.contains("Third");
		set.remove("Fourth");

		System.out.println("isEmpty: " + isEmpty);
		System.out.println("size: " + size);
		System.out.println("containsEntry: " + containsEntry);

		// output elements using enhanced for loop
		for (String s : set) {
			System.out.println(s);
		}

		// output elements using iterator
		System.out.println("\nIterator output");
		Iterator<String> iter = set.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}
}
Output
isEmpty: false
size: 4
containsEntry: true
Second
Third
First

Iterator output
Second
Third
First