Set Interface in Java
The Set interface in Java is a child interface of Collection that is used to store a group of elements with no duplicates. If you try to add an element that is already in the set, the set simply ignores it. Sets are useful for things like unique email addresses, distinct words in a text, or the tags on an article. In this lesson, you will learn the features of Set, its implementations, and how to perform union, intersection and difference.
Declaration
public interface Set<E> extends Collection<E>Set adds no new methods to Collection. What changes is the rule: no two elements may be equal according to equals.
Features of Set
- No duplicates: adding an existing element returns
falseand changes nothing. - No index: there is no
get(i); elements are reached by iterating. - Order depends on the class:
HashSethas no order,LinkedHashSetkeeps insertion order,TreeSetkeeps sorted order. - Fast lookup:
containsis very fast inHashSet.
Implementation Classes
| Class | Order | Allows null | Internal structure |
|---|---|---|---|
HashSet | No guaranteed order | Yes, one | Hash table (a HashMap) |
LinkedHashSet | Insertion order | Yes, one | Hash table plus a linked list |
TreeSet | Sorted order | No | Red-black tree |
EnumSet | Enum declaration order | No | Bit vector |
Example: Duplicates Are Ignored
Let's see an example where a name is added twice.
import java.util.LinkedHashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<String> names = new LinkedHashSet<>();
System.out.println(names.add("Navika"));
System.out.println(names.add("Srihitha"));
System.out.println(names.add("Navika"));
names.add("Advitha");
System.out.println(names);
System.out.println("Size: " + names.size());
}
}true
true
false
[Navika, Srihitha, Advitha]
Size: 3Explanation: The second add("Navika") returns false because Navika is already in the set, so the set still has 3 names. A LinkedHashSet is used here so the printed order matches the insertion order.
Set Operations
Sets support the operations from mathematics through Collection methods:
| Operation | Method | Result |
|---|---|---|
| Union | a.addAll(b) | Elements in either set |
| Intersection | a.retainAll(b) | Elements in both sets |
| Difference | a.removeAll(b) | Elements in a but not in b |
| Subset check | a.containsAll(b) | true if every element of b is in a |
import java.util.Set;
import java.util.TreeSet;
public class SetOps {
public static void main(String[] args) {
Set<String> navika = Set.of("Java", "Python", "SQL");
Set<String> advitha = Set.of("Java", "C", "SQL");
Set<String> union = new TreeSet<>(navika);
union.addAll(advitha);
System.out.println("Union: " + union);
Set<String> both = new TreeSet<>(navika);
both.retainAll(advitha);
System.out.println("Intersection: " + both);
Set<String> onlyNavika = new TreeSet<>(navika);
onlyNavika.removeAll(advitha);
System.out.println("Difference: " + onlyNavika);
}
}Union: [C, Java, Python, SQL]
Intersection: [Java, SQL]
Difference: [Python]Explanation: Each operation works on a fresh copy, because addAll, retainAll and removeAll change the set they are called on. TreeSet copies are used so the output is sorted and easy to read.
Common Mistakes
Expecting HashSet to keep insertion order. Use LinkedHashSet for that.
Storing objects without equals and hashCode. Two "equal" objects are then both kept (see "HashSet in Java").
Changing a field used by hashCode after adding an object. The set can no longer find it.
Practice
- Easy: Read a sentence, split it into words, and print the number of distinct words.
- Harder: Given two lists of student names for two clubs, print who is in both clubs, who is in only one, and everyone in total, sorted.
Key Takeaways
Was this tutorial helpful?