TheDeveloperBlog.com


Java

Java HashSet Examples

HashSet. A set has unique elements. With HashSet, we create a set of elements. No duplicates are allowed. And with helpful methods, we compare and test elements.


Similar to HashMap. The HashSet is a set collection. It stores only one of each unique key. Two keys are never equal, and with hashing, this is easily detected.


Start. We create a HashSet with String elements. The String type is specified in the type itself. On the right side of the allocation, by "new HashSet," we use the diamond inference syntax.

Tip: With diamond inference, we do not need to specify the String type. The type is read from the left side.

String: This example uses the String type for the HashSet. But other types, like Integer, also work.

Based on:

Java 7

Java program that uses HashSet

import java.util.HashSet;

public class Program {
    public static void main(String[] args) {

	// Create HashSet.
	HashSet<String> hash = new HashSet<>();
	hash.add("castle");
	hash.add("bridge");
	hash.add("castle"); // Duplicate element.
	hash.add("moat");

	// Display size.
	System.out.println(hash.size());

	// See if these three elements exist.
	System.out.println(hash.contains("castle"));
	System.out.println(hash.contains("bridge"));
	System.out.println(hash.contains("moat"));
    }
}

Output

3
true
true
true

Above, we added four elements to the HashSet. Three of them are unique. But we add the String "castle" twice. This duplicate element is not added to the HashSet. It already exists.


Size. We call the size() method. This tells us how many unique elements (integers here) are stored. If the set is empty, size returns zero. IsEmpty returns true when there are no elements.

Here: We create a new HashSet, which has size 0 and is empty. We then add an element. Size() now returns 1.

Java program that uses size, isEmpty

import java.util.HashSet;

public class Program {
    public static void main(String[] args) {

	HashSet<Integer> hash = new HashSet<>();

	// Zero elements.
	System.out.println(hash.size());
	System.out.println(hash.isEmpty());
	System.out.println();

	// Add one element.
	hash.add(10);

	System.out.println(hash.size());
	System.out.println(hash.isEmpty());
    }
}

Output

0
true

1
false

Contains. We use the contains() method. This receives an argument of the HashSet's specified element type. It returns true if the element exists. It returns false if no element is found.


AddAll, containsAll. We call addAll() to add the ArrayList elements to the HashSet. We also invoke containsAll. This returns true only if all elements from the collection are present.

Tip: If the ArrayList were to contain duplicate Strings, these would be eliminated as they are added to the HashSet.

ArrayList
Java program that uses addAll, containsAll

import java.util.ArrayList;
import java.util.HashSet;

public class Program {
    public static void main(String[] args) {

	// An ArrayList of three Strings.
	ArrayList<String> list = new ArrayList<>();
	list.add("socrates");
	list.add("plato");
	list.add("cebes");

	// Add all elements to HashSet.
	HashSet<String> hash = new HashSet<>();
	hash.addAll(list);

	// Use contains.
	boolean a = hash.contains("cebes");
	System.out.println(a);

	// Use containsAll.
	boolean b = hash.containsAll(list);
	System.out.println(b);
    }
}

Output

true
true

RetainAll. This is a union method. We pass a collection to retainAll. The set is then modified to include only those elements that both the collection and the set itself have.

Union: Here the two collections (the ArrayList and the HashSet) have two elements in common: 2 and 3. These are the retained values.

Java program that uses retainAll

import java.util.ArrayList;
import java.util.HashSet;

public class Program {
    public static void main(String[] args) {

	// This ArrayList contains 1, 2 and 3.
	ArrayList<Integer> list = new ArrayList<>();
	list.add(1);
	list.add(2);
	list.add(3);

	// This HashSet has 2, 3 and 4.
	HashSet<Integer> set = new HashSet<>();
	set.add(2);
	set.add(3);
	set.add(4);

	// Retain only 2 and 3.
	set.retainAll(list);

	for (Integer value : set) {
	    System.out.println(value);
	}
    }
}

Output

2
3

Static field. As with other collections, a HashSet can be used as a static field. This enables us to use a single HashSet across methods without worrying about passing parameters.

Caution: Using static fields in this way can lead to code that is hard to follow and easily broken. Please use caution.

Static
Java program that uses static HashSet

import java.util.HashSet;

public class Program {

    static HashSet<Integer> used = new HashSet<>();

    static void addMore() {
	used.add(1000);
	used.add(0);
    }

    public static void main(String[] args) {

	used.add(10);
	used.add(100);

	// Call another method that uses the HashSet.
	addMore();

	// Test the set.
	if (used.contains(1000)) {
	    System.out.println(1000);
	}
    }
}

Output

1000

HashSet enforces uniqueness. It does not allow duplicate elements. In this way, it is a HashMap but with no values—it has only keys. In some program contexts this is clearer.