HashSet. With a HashSet we have a set collection of any element type. HashSet stores only one of each unique key—2 keys are never equal. With hashing duplicates are easily detected.
A HashSet can be thought of like a HashMap with no values. Sometimes, HashSet can make code clearer because it only uses keys, not values.
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.
Detail This example uses the String type for the HashSet. But other types, like Integer, also work.
Next 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.
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"));
}
}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.
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());
}
}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.
Detail We call the addAll() method to add the ArrayList elements to the HashSet.
Also We 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.
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);
}
}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.
Here The two collections (the ArrayList and the HashSet) have two elements in common: 2 and 3. These are the retained values.
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);
}
}
}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.
Warning Using static fields in this way can lead to code that is hard to follow and easily broken. Please use caution.
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);
}
}
}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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 21, 2023 (edit).