Java
Module 16: Java Collections FrameworkBeginner28 min read

Set, HashMap Internals, TreeMap & Comparable vs Comparator

Understand HashSet, LinkedHashSet, TreeSet, HashMap bucket/hashing internals (Java 8 treeification), and Comparable vs Comparator.

Key Takeaways & Core Concepts
  • `HashSet`: Unordered, O(1) average lookup/insert, backed internally by a HashMap where each element is a key mapped to a dummy PRESENT object.
  • `LinkedHashSet`: Preserves insertion order using a doubly-linked list across entries.
  • `TreeSet`: Backed by a Red-Black self-balancing BST; keeps elements sorted in O(log n) time and disallows null.

Set Implementations

  • `HashSet`: Unordered, O(1) average lookup/insert, backed internally by a HashMap where each element is a key mapped to a dummy PRESENT object.
  • `LinkedHashSet`: Preserves insertion order using a doubly-linked list across entries.
  • `TreeSet`: Backed by a Red-Black self-balancing BST; keeps elements sorted in O(log n) time and disallows null.
HashMap Frequency Counter & Custom Comparator
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 String[] words = {"java", "spring", "java", "jvm", "spring", "java"};
6 Map<String, Integer> freq = new HashMap<>();
7 for (String w : words) freq.merge(w, 1, Integer::sum);
8
9 freq.entrySet().stream()
10 .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
11 .forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));
12 }
13}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: `Map.Entry.comparingByValue().reversed()` sorts map entries from highest to lowest frequency.

Internal Working of HashMap (Deep Dive)

HashMap<K, V> stores entries in a Node<K, V>[] table (default initial capacity 16, default load factor 0.75, so it resizes at 16 * 0.75 = 12 entries):

  1. 1
    Hash Computation: Calls key.hashCode() and applies (h = key.hashCode()) ^ (h >>> 16) so high bits also influence bucket selection.
  2. 2
    Bucket Index: (n - 1) & hash (fast bitwise modulo because n is always a power of 2).
  3. 3
    Collision Handling: If two keys map to the same bucket, HashMap checks key.equals() along a linked list. In Java 8+, when a bucket reaches TREEIFY_THRESHOLD = 8 (and table length >= 64), the linked list converts into a Red-Black tree, improving worst-case lookup from O(n) to O(log n)!
  4. 4
    Thread Safety: HashMap is not thread-safe (concurrent writes can corrupt structure or lose updates). Use ConcurrentHashMap in multithreaded code.

Comparable vs Comparator

  • `Comparable<T>` (java.lang): Defines the class's single natural ordering via int compareTo(T other).
  • `Comparator<T>` (java.util): Defines external, reusable sort orders without modifying the domain class (e.g., Comparator.comparing(User::getScore).reversed()).
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)