HashSet: no duplicates
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A set is a collection that never holds the same value twice. HashSet is the most used set in Java: it drops duplicates for you and answers "is this value here?" very fast.
What a set is
A set is a collection that holds each value at most once and has no positions. Two values count as the same when equals says so.
A set holds each value at most once. Think of today's attendance sheet: a student is either on it or not, and writing the same name twice does not make them "more present". The code below adds Pune twice.
Set<String> cities = new HashSet<>();cities.add("Pune");cities.add("Pune"); // already there: not added againSystem.out.println(cities.size()); // 1cities.get(0); // error: cannot find symbolIn Java, Set is an interface in java.util, and HashSet is the class you usually create. As with lists, declare the variable with the interface type: Set<String> cities = new HashSet<>();.
A set has no positions. There is no get(0) and no set(1, x). You add values, remove values, loop over them, and ask one main question: is this value in the set?
add, contains, remove and size
A duplicate is a value that equals says is the same as one the set already holds. add refuses it: it returns false and the set does not change.
Most Set methods return a boolean that tells you what happened. This is more useful than it looks: one call to add both stores the value and tells you whether you had seen it before. The snippet below shows each return value.
Set<String> orders = new HashSet<>();orders.add("ORD101"); // true: a new valueorders.add("ORD101"); // false: already thereorders.contains("ORD101"); // trueorders.remove("ORD999"); // false: it was not thereadd(x): addsxand returnstrue; ifxis already there, it changes nothing and returnsfalse.contains(x):trueifxis in the set.remove(x): removesxand returnstrue; returnsfalseifxwas not there.size(),isEmpty()andclear()work as in a list.new HashSet<>(list)copies a list and drops its duplicates.
Example 1 · Add, check and remove
import java.util.HashSet;import java.util.Set;
public class HashSetBasicsDemo { public static void main(String[] args) { Set<String> cities = new HashSet<>(); System.out.println(cities.add("Pune")); System.out.println(cities.add("Delhi")); System.out.println(cities.add("Pune")); System.out.println("Size: " + cities.size()); System.out.println("Has Delhi? " + cities.contains("Delhi")); System.out.println("Has Goa? " + cities.contains("Goa")); System.out.println("Removed Goa? " + cities.remove("Goa")); System.out.println("Removed Delhi? " + cities.remove("Delhi")); System.out.println(cities); }}true true false Size: 2 Has Delhi? true Has Goa? false Removed Goa? false Removed Delhi? true [Pune]
What this code does
- The second
add("Pune")returnsfalse: the value is already there, so the set does not change and the size stays 2. removealso reports what happened:falseforGoa, which was never added, andtrueforDelhi.
Example 2 · Unique students at the library gate
import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;
public class LibraryGateDemo { public static void main(String[] args) { int[] scans = { 104, 101, 104, 107, 102, 101, 110, 104, 107, 103 };
Set<Integer> visitors = new HashSet<>(); for (int roll : scans) { visitors.add(roll); }
System.out.println("Total scans: " + scans.length); System.out.println("Unique students: " + visitors.size()); System.out.println("Did 105 visit? " + visitors.contains(105));
List<Integer> report = new ArrayList<>(visitors); Collections.sort(report); System.out.println("Roll numbers: " + report); }}Total scans: 10 Unique students: 6 Did 105 visit? false Roll numbers: [101, 102, 103, 104, 107, 110]
What this code does
- A student who scans the card three times is still one visitor. The set drops the extra scans by itself, with no
ifneeded. visitors.add(roll)turns theintinto anIntegerautomatically (autoboxing), because collections hold objects only.
Example 3 · Catch a repeated UPI request
import java.util.HashSet;import java.util.Set;
public class UpiDuplicateDemo { public static void main(String[] args) { String[] ids = { "TXN501", "TXN502", "TXN501", "TXN503", "TXN502" }; int[] amounts = { 250, 120, 250, 80, 120 };
Set<String> processed = new HashSet<>(); int total = 0;
for (int i = 0; i < ids.length; i++) { if (processed.add(ids[i])) { total = total + amounts[i]; System.out.println("Paid Rs. " + amounts[i] + " for " + ids[i]); } else { System.out.println("Duplicate ignored: " + ids[i]); } } System.out.println("Money taken: Rs. " + total); }}Paid Rs. 250 for TXN501 Paid Rs. 120 for TXN502 Duplicate ignored: TXN501 Paid Rs. 80 for TXN503 Duplicate ignored: TXN502 Money taken: Rs. 450
What this code does
- Payment apps sometimes send the same request twice when the network is slow. Charging twice would be a serious bug.
processed.add(id)istrueonly the first time an id is seen, so one call both records the id and decides whether to pay.
Predict the output
What does add return?
Read the code and pick what it prints.
Round 1 of 2
Which three lines are printed?
equals. So "Pune" and "pune" are two different values, and so are "Pune" and "Pune " with a space.No order is guaranteed
A HashSet is the most used Set class. It stores each value in a place chosen from its hash code, so add, contains and remove are fast, but the order is not guaranteed.
A HashSet stores each value at a place worked out from its hashCode(). So printing it or looping over it gives an order that is neither the order you added nor sorted. The examples below show this.
Example 4 · The order is not the order you added
import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;
public class HashSetOrderDemo { public static void main(String[] args) { Set<String> names = new HashSet<>(); names.add("Rohan"); names.add("Priya"); names.add("Arjun"); names.add("Kavya"); names.add("Diya");
System.out.println("Printed: " + names);
for (String name : names) { System.out.print(name + " "); } System.out.println();
List<String> sorted = new ArrayList<>(names); Collections.sort(sorted); System.out.println("Sorted: " + sorted); }}Printed: [Priya, Kavya, Arjun, Diya, Rohan] Priya Kavya Arjun Diya Rohan Sorted: [Arjun, Diya, Kavya, Priya, Rohan]
What this code does
- Rohan was added first but prints last. Printing and the for-each loop both follow the set's internal order, which Java does not promise.
new ArrayList<>(names)copies the set into a list, andCollections.sortputs it in a fixed, readable order.
Example 5 · Mistake: asking a set for an index
import java.util.HashSet;import java.util.Set;
public class SetIndexDemo { public static void main(String[] args) { Set<String> subjects = new HashSet<>(); subjects.add("Maths"); subjects.add("Physics"); System.out.println(subjects.get(0)); }}SetIndexDemo.java:9: error: cannot find symbol
System.out.println(subjects.get(0));
^
symbol: method get(int)
location: variable subjects of type Set<String>
1 errorWhat this code does
Sethas noget(int)method, because a set has no first or second position.- To visit the values, use a for-each loop. To pick by position, copy the set into a list first:
new ArrayList<>(subjects).
This order can change when the set grows, and it can differ between Java versions. Never write code that depends on it. The outputs in this lesson show what Java 17 prints for this data, but treat that order as an accident.
When the order matters, copy the set into an ArrayList and sort it, as in the first example above. The next lessons show LinkedHashSet (keeps insertion order) and TreeSet (keeps values sorted).
Integer values often print in sorted order, by accident. Add bigger or more values and the order changes. Do not trust it.Why HashSet is fast
Hashing turns a value into a number, its hash code, with hashCode(). A HashSet uses that number to pick a bucket: a small group of stored values. Only that bucket is searched with equals.
list.contains(x) checks the elements one by one. With 1 lakh roll numbers, a missing value means 1 lakh checks. The code below compares a list and a set of 1 lakh numbers.
List<Integer> rollList = new ArrayList<>();Set<Integer> rollSet = new HashSet<>();for (int r = 1; r <= 100000; r++) { rollList.add(r); rollSet.add(r);}rollList.contains(0); // checks all 1 lakh values before saying falserollSet.contains(0); // hashCode() picks one bucket, then a few equals checksA HashSet first calls x.hashCode(). That number points straight to a small group of stored values, called a bucket. Only the values in that bucket are compared with equals. So add, contains and remove take about the same short time whether the set holds 10 values or 10 lakh. In big-O words, they are O(1) on average.
This is why a set is the right tool for "have I seen this before?" checks. For String and Integer, equals and hashCode are already written. How equals and hashCode work is explained in the hashCode method (opens in a new tab); your own classes need both, as the next lesson shows.
Fixed sets with Set.of
Set.of("UPI", "Card", "Cash") makes a small set that can never change, just like List.of. Calling add or remove on it throws UnsupportedOperationException. The example below checks values, then breaks the rules.
Example 6 · Set.of: fixed, and strict about duplicates
import java.util.Set;
public class SetOfDemo { public static void main(String[] args) { Set<String> modes = Set.of("UPI", "Card", "Cash"); System.out.println("Card allowed? " + modes.contains("Card")); System.out.println("Cheque allowed? " + modes.contains("Cheque"));
Set<String> wrong = Set.of("UPI", "Card", "UPI"); System.out.println(wrong.size()); }}Card allowed? true Cheque allowed? false Exception in thread "main" java.lang.IllegalArgumentException: duplicate element: UPI at java.base/java.util.ImmutableCollections$SetN.<init>(ImmutableCollections.java:918) at java.base/java.util.Set.of(Set.java:505) at SetOfDemo.main(SetOfDemo.java:9)
What this code does
Set.ofis handy for a fixed list of allowed values.containschecks a value quickly.- A repeated value in
Set.ofis treated as a programming mistake, so it crashes.HashSet.addwould quietly returnfalseinstead.
Set.of is stricter than HashSet in two ways. A duplicate value throws IllegalArgumentException at once, instead of being dropped quietly. And it does not accept null. Its order is not guaranteed either; it can even change from one run of the program to the next.
Next step
Check your understanding
12 quick questions