Java Tutorial · Collections · Lesson 27 of 37

Java HashSet

Store unique values and use set operations.

HashSet

A Set contains no duplicates. add() returns false if the item was already there:

Example 1
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<String> tags = new TreeSet<>();
        System.out.println(tags.add("java"));
        System.out.println(tags.add("spring"));
        System.out.println(tags.add("java"));   // duplicate
        System.out.println(tags + " " + tags.size() + " " + tags.contains("spring"));
        List<Integer> withDupes = List.of(3, 1, 3, 2, 1);
        System.out.println(new TreeSet<>(withDupes));
    }
}

Output

true
true
false
[java, spring] 2 true
[1, 2, 3]

Run this on your computer — see “Get Started” for setup.

Set operations

addAll (union), retainAll (intersection) and removeAll (difference):

Example 2
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<String> alice = new TreeSet<>(Set.of("java", "sql", "docker"));
        Set<String> bob = new TreeSet<>(Set.of("java", "python", "sql"));
        Set<String> both = new TreeSet<>(alice);
        both.retainAll(bob);
        Set<String> either = new TreeSet<>(alice);
        either.addAll(bob);
        Set<String> onlyAlice = new TreeSet<>(alice);
        onlyAlice.removeAll(bob);
        System.out.println("both: " + both);
        System.out.println("either: " + either);
        System.out.println("only Alice: " + onlyAlice);
    }
}

Output

both: [java, sql]
either: [docker, java, python, sql]
only Alice: [docker]

Run this on your computer — see “Get Started” for setup.

Like maps, use LinkedHashSet to keep insertion order or TreeSet for sorted order.

Test yourself

What does set.add(x) return if x is already in the set?

  1. true
  2. false
  3. null
  4. It throws an exception
Show answer

Answer: false

Practice next