Skip to main content
Advertisement

11.3 HashSet and TreeSet

Set is a collection that directly implements the mathematical concept of a Set— a group that tolerates no duplicates. If you try to store the same value twice, it will be silently ignored. Use a Set primarily when you need to ** verify whether an element exists, or keep only uniquely distinct data without any duplicates**.

1. HashSet

This is the most commonly used Set implementation. It does not guarantee any particular storage order(the order you retrieve elements may differ from the order you inserted them).

import java.util.HashSet;

HashSet<String> tags = new HashSet<>();

// 1. add(): Add an element
tags.add("Java");
tags.add("Spring");
tags.add("MySQL");
tags.add("Java"); // Duplicate! Automatically ignored.

System.out.println(tags); // [Spring, Java, MySQL] (order varies)
System.out.println(tags.size()); // 3 (after removing duplicate)

// 2. contains(): Check if an element exists (extremely fast - O(1))
System.out.println(tags.contains("Java")); // true
System.out.println(tags.contains("Python")); // false

// 3. remove(): Delete an element
tags.remove("MySQL");
System.out.println(tags); // [Spring, Java]

Real-world HashSet Use Case: Removing Duplicates

import java.util.ArrayList;
import java.util.HashSet;

ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Alice"); // Duplicate!
names.add("Bob"); // Duplicate!

// Simply pour the ArrayList into a HashSet to automatically eliminate duplicates!
HashSet<String> uniqueNames = new HashSet<>(names);
System.out.println(uniqueNames); // [Bob, Charlie, Alice]
System.out.println("Unique count: " + uniqueNames.size()); // 3

2. TreeSet

TreeSet automatically sorts the elements as they are stored. By default, it sorts in ascending order (numbers: smallest first, strings: alphabetical order). If you don't need sorting, use the faster HashSet instead.

import java.util.TreeSet;

TreeSet<Integer> scores = new TreeSet<>();
scores.add(85);
scores.add(92);
scores.add(70);
scores.add(100);
scores.add(85); // Duplicate removed

System.out.println(scores); // [70, 85, 92, 100] (automatically sorted ascending!)

// Instantly retrieving min and max values
System.out.println("Min: " + scores.first()); // 70
System.out.println("Max: " + scores.last()); // 100
Advertisement