Set HashSet and TreeSet

No Duplicates

A Set stores each element only once. add returns false if the element is already there.

ImplementationOrderSpeed
HashSetno guaranteed orderO(1)
LinkedHashSetinsertion orderO(1)
TreeSetsorted (natural or Comparator)O(log n)

Three Sets Side by Side

Example

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("Goa", "Delhi", "Agra", "Goa", "Jaipur", "Delhi");

        Set<String> hash = new HashSet<>(visits);
        Set<String> linked = new LinkedHashSet<>(visits);
        TreeSet<String> tree = new TreeSet<>(visits);

        System.out.println("HashSet       " + hash + " size=" + hash.size());
        System.out.println("LinkedHashSet " + linked);
        System.out.println("TreeSet       " + tree);
        System.out.println("add Goa again: " + linked.add("Goa"));
        System.out.println("first/last: " + tree.first() + " / " + tree.last());
        System.out.println("after Delhi: " + tree.higher("Delhi"));
    }
}

Output

HashSet       [Delhi, Jaipur, Goa, Agra] size=4
LinkedHashSet [Goa, Delhi, Agra, Jaipur]
TreeSet       [Agra, Delhi, Goa, Jaipur]
add Goa again: false
first/last: Agra / Jaipur
after Delhi: Goa

Note: The HashSet order shown above is just how this JVM laid out the buckets. Never rely on it.

Set Operations

Example

Union, intersection and difference with addAll, retainAll and removeAll.

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

public class Main {
    public static void main(String[] args) {
        Set<String> asha = Set.of("Java", "SQL", "React");
        Set<String> ravi = Set.of("Java", "Python", "SQL");

        Set<String> union = new TreeSet<>(asha);
        union.addAll(ravi);
        Set<String> common = new TreeSet<>(asha);
        common.retainAll(ravi);
        Set<String> onlyAsha = new TreeSet<>(asha);
        onlyAsha.removeAll(ravi);

        System.out.println("All skills : " + union);
        System.out.println("Common     : " + common);
        System.out.println("Only Asha  : " + onlyAsha);
    }
}

Output

All skills : [Java, Python, React, SQL]
Common     : [Java, SQL]
Only Asha  : [React]