What if you have a list of items and you want to make sure there are no duplicates? You could check every time you add something, but that gets messy fast.
A HashSet solves this problem automatically. It only stores unique elements โ if you try to add a duplicate, the set simply ignores it.
Creating a HashSet
Like ArrayList and HashMap, HashSet is in the java.util package.
Specify the element type in angle brackets.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet names = new HashSet<>();
}
}
This creates a set that will hold String objects. You can use any
type you want โ String, Integer, or your own custom classes.
Adding and Removing Elements
Use add() to insert and remove() to delete. If you add
a duplicate, nothing happens โ no error, no crash, just no change.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet names = new HashSet<>();
names.add("Amina");
names.add("Musa");
names.add("Fatima");
names.add("Amina");
System.out.println(names.size());
names.remove("Musa");
System.out.println(names.size());
}
}
Even though we added "Amina" twice, the size is 3 โ not 4. The set silently ignored the duplicate. After removing "Musa", the size drops to 2.
Checking if an Element Exists
Use contains() to check if an element is in the set. It is fast โ
much faster than checking an ArrayList.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet names = new HashSet<>();
names.add("Amina");
names.add("Musa");
if (names.contains("Amina")) {
System.out.println("Amina is in the set");
}
if (!names.contains("John")) {
System.out.println("John is not here");
}
}
}
contains() returns true or false. It is
perfect for checks like "is this username already taken?" or "have we seen this
item before?"
Iterating Over a HashSet
You can loop through a HashSet with a for-each loop, just like ArrayList. But remember โ sets do not have indexes and the order is not guaranteed.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet names = new HashSet<>();
names.add("Amina");
names.add("Musa");
names.add("Fatima");
for (String name : names) {
System.out.println(name);
}
}
}
Each element appears exactly once when you iterate. The order might surprise you โ
it is not the same order you added them. That is fine for most use cases. If you
need ordering, look at LinkedHashSet or TreeSet.