Reading history

Java HashSet, LinkedHashSet and TreeSet

4 min read 0 views

Learn Java sets: removing duplicates, HashSet vs LinkedHashSet vs TreeSet ordering, union, intersection and difference, and TreeSet navigation methods.

A Set is a collection that never holds the same element twice. It is the natural choice for removing duplicates, checking membership quickly and comparing groups, such as finding students enrolled in both of two courses. Java offers three main implementations, HashSet, LinkedHashSet and TreeSet, which differ mainly in the order they keep.

In this lesson you will learn

  • How sets reject duplicates
  • HashSet, LinkedHashSet and TreeSet ordering
  • What add() returns
  • Union, intersection and difference
  • Range methods of TreeSet

Three Kinds of Set

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        List<String> visits = List.of("Dhaka", "Sylhet", "Dhaka", "Cox's Bazar", "Sylhet", "Bogura");

        Set<String> hash = new HashSet<>(visits);
        Set<String> linked = new LinkedHashSet<>(visits);
        Set<String> tree = new TreeSet<>(visits);
        System.out.println("Unique count: " + hash.size());
        System.out.println("LinkedHashSet (insertion order): " + linked);
        System.out.println("TreeSet (sorted): " + tree);

        System.out.println("add Dhaka again? " + hash.add("Dhaka"));
        System.out.println("add Rangpur? " + hash.add("Rangpur"));
    }
}

Output

Unique count: 4
LinkedHashSet (insertion order): [Dhaka, Sylhet, Cox's Bazar, Bogura]
TreeSet (sorted): [Bogura, Cox's Bazar, Dhaka, Sylhet]
add Dhaka again? false
add Rangpur? true
  • Six visits contain only four distinct cities, so every set has size 4.
  • HashSet is the fastest but gives no order guarantee, so its printed order can look random.
  • LinkedHashSet remembers the order elements were first added, which makes it ideal for “remove duplicates but keep the order”.
  • TreeSet keeps elements sorted.
  • add() returns false when the element is already present, which is a handy way to detect duplicates.

Set Operations and TreeSet Navigation

import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<String> python = new TreeSet<>(Set.of("Nadia", "Rafi", "Mitu", "Arif"));
        Set<String> java   = new TreeSet<>(Set.of("Rafi", "Tania", "Arif", "Imran"));

        Set<String> union = new TreeSet<>(python);
        union.addAll(java);
        Set<String> both = new TreeSet<>(python);
        both.retainAll(java);
        Set<String> onlyPython = new TreeSet<>(python);
        onlyPython.removeAll(java);

        System.out.println("Union:        " + union);
        System.out.println("Intersection: " + both);
        System.out.println("Difference:   " + onlyPython);

        TreeSet<Integer> scores = new TreeSet<>(Set.of(45, 70, 82, 90, 66));
        System.out.println("first=" + scores.first() + " last=" + scores.last()
                + " ceiling(75)=" + scores.ceiling(75) + " headSet(70)=" + scores.headSet(70));
    }
}

Output

Union:        [Arif, Imran, Mitu, Nadia, Rafi, Tania]
Intersection: [Arif, Rafi]
Difference:   [Mitu, Nadia]
first=45 last=90 ceiling(75)=82 headSet(70)=[45, 66]
  • Union: copy one set and addAll the other.
  • Intersection: copy and retainAll, which keeps only elements also in the other set.
  • Difference: copy and removeAll.
  • Each operation changes the set it is called on, so work on a copy to keep the original.
  • TreeSet adds navigation methods: first, last, ceiling(x) (smallest element ≥ x), floor(x), and headSet(x) (elements below x).

Comparison

TypeOrderadd / containsNulls
HashSetNone guaranteedO(1) averageOne allowed
LinkedHashSetInsertion orderO(1) averageOne allowed
TreeSetSortedO(log n)Not allowed

A HashSet is built on a HashMap internally, so the same rules apply: elements need consistent equals() and hashCode(). A TreeSet needs elements that are Comparable, or a Comparator passed to its constructor.

Common Mistakes

  1. Expecting a HashSet to print in insertion or sorted order.
  2. Storing custom objects without overriding equals and hashCode, so “equal” objects are treated as different.
  3. Using retainAll on the original set and losing data you needed.
  4. Trying to get an element by index; sets have no get(i).

Practice Exercises

Exercise 1. Remove duplicate numbers from a list while keeping their first-seen order.

Show answer
List<Integer> nums = List.of(5, 3, 5, 1, 3, 9);
List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(nums));
System.out.println(unique);   // [5, 3, 1, 9]

Exercise 2. Find the first repeated word in "to be or not to be".

Show answer
Set<String> seen = new HashSet<>();
for (String w : "to be or not to be".split(" ")) {
    if (!seen.add(w)) { System.out.println(w); break; }   // prints "to"
}

Frequently Asked Questions

Is contains() faster on a set than on a list?

Yes. HashSet.contains is O(1) on average, while ArrayList.contains checks elements one by one, which is O(n).

How do I sort a set in reverse order?

Create the TreeSet with a comparator: new TreeSet<>(Comparator.reverseOrder()), or call descendingSet() on an existing one.

Summary

  • Sets store unique elements; add returns false for duplicates.
  • HashSet is fastest, LinkedHashSet keeps insertion order, TreeSet keeps elements sorted.
  • addAll, retainAll and removeAll give union, intersection and difference.
  • Elements need correct equals/hashCode (or comparability for TreeSet).

Next: Java Generics.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *