HomeSearch

Java HashSet Examples

Test for element existence and uniqueness by adding elements to the HashSet collection.
HashSet. Examine a collection of shells from the beach. Each one is different. There are no duplicates. This is a set of seashells.
With a HashSet we have a set collection of any element type. HashSet stores only one of each unique key. Two keys are never equal. With hashing duplicates are easily detected.
A start. We create a HashSet with Strings. 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.

Program: We add 4 elements to the HashSet. Three of them are unique. But we add the String "castle" twice.

Info: The duplicate element "castle" is not added to the HashSet. It already exists.

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
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: We call the addAll() method to add the ArrayList elements to the HashSet.

ContainsAll: 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 Initializer
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
A summary. 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 programs this is clearer.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls