Set Interface in Java

Naveen AnamaneniUpdated · 4 min read

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

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 false and changes nothing.
  • No index: there is no get(i); elements are reached by iterating.
  • Order depends on the class: HashSet has no order, LinkedHashSet keeps insertion order, TreeSet keeps sorted order.
  • Fast lookup: contains is very fast in HashSet.

Implementation Classes

ClassOrderAllows nullInternal structure
HashSetNo guaranteed orderYes, oneHash table (a HashMap)
LinkedHashSetInsertion orderYes, oneHash table plus a linked list
TreeSetSorted orderNoRed-black tree
EnumSetEnum declaration orderNoBit vector

Example: Duplicates Are Ignored

Let's see an example where a name is added twice.

SetDemo.java▶ Try it
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());
    }
}
Output
true
true
false
[Navika, Srihitha, Advitha]
Size: 3

Explanation: 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:

OperationMethodResult
Uniona.addAll(b)Elements in either set
Intersectiona.retainAll(b)Elements in both sets
Differencea.removeAll(b)Elements in a but not in b
Subset checka.containsAll(b)true if every element of b is in a
SetOps.java▶ Try it
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);
    }
}
Output
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

  1. Easy: Read a sentence, split it into words, and print the number of distinct words.
  2. 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.

Quick check: Set interface

4 questions
1What happens when you add a duplicate to a Set?
2Which set keeps insertion order?
3Which method computes an intersection?
4Does Set have a get(int index) method?

Key Takeaways

Was this tutorial helpful?

Lesson 272 of 482