You're tracking which pages a user has visited. You don't want duplicates, and you need fast "have they seen this?" checks. HashSet automatically ignores duplicates and provides O(1) membership testing.

Collect unique tags

Add items to a set - duplicates are ignored.

UniqueTags.java
Replay: real traced execution (multi-file project)
import java.util.HashSet;

public class UniqueTags {
    public static void main(String[] args) {
        // Create a set of tags for a blog post
        HashSet<String> tags = new HashSet<>();

        System.out.println("=== Adding Blog Tags ===");

        // Add tags
        boolean added;

        added = tags.add("java");
        System.out.println("Add 'java': " + added + " → " + tags);

        added = tags.add("programming");
        System.out.println("Add 'programming': " + added + " → " + tags);

        added = tags.add("tutorial");
        System.out.println("Add 'tutorial': " + added + " → " + tags);

        // Try to add duplicate
        added = tags.add("java");
        System.out.println("Add 'java' again: " + added + " → " + tags);
        System.out.println("Duplicate ignored!");

        // Add more tags
        tags.add("beginner");
        tags.add("coding");
        tags.add("java");
        System.out.println("\nWith more tags: " + tags);

        System.out.println("\n=== Blog Post Tags ===");
        System.out.println("Total unique tags: " + tags.size());
        System.out.println("Tags: " + tags);

        // Display as hashtags
        System.out.println("\n=== Formatted ===");
        for (String tag : tags) {
            System.out.print("#" + tag + " ");
        }
        System.out.println();
    }
}
  1. tags ← [], added ← true

    4public class UniqueTags {5    public static void main(String[] args) {6        // Create a set of tags for a blog post  //#?create7        HashSet<String> tags→ [] = new HashSet<>();8        9        System.out.println("=== Adding Blog Tags ===");10        11        // Add tags  //#?add12        boolean added;13        14        added→ true = tags.add("java");15        System.out.println("Add 'java': " + addedtrue + " → " + tags[java]);16        17        added→ true = tags.add("programming");18        System.out.println("Add 'programming': " + addedtrue + " → " + tags[java, programming]);19        20        added→ true = tags.add("tutorial");21        System.out.println("Add 'tutorial': " + addedtrue + " → " + tags[java, tutorial, programming]);22        23        // Try to add duplicate  //#?duplicate24        added→ false = tags.add("java");25        System.out.println("Add 'java' again: " + addedfalse + " → " + tags[java, tutorial, programming]);26        System.out.println("Duplicate ignored!");27        28        // Add more tags29        tags.add("beginner");  //@var=_,!30        tags.add("coding");    //@var=_,!31        tags.add("java");      //@var=_,!  // Still ignored32        System.out.println("\nWith more tags: " + tags[coding, java, beginner, tutorial, programming]);  //@var=_,!33        34        System.out.println("\n=== Blog Post Tags ===");35        System.out.println("Total unique tags: " + tags.size());36        System.out.println("Tags: " + tags[coding, java, beginner, tutorial, programming]);37        38        // Display as hashtags39        System.out.println("\n=== Formatted ===");40        for (String tag : tags) {
    output=== Adding Blog Tags ===
    Add 'java': true → [java]
    Add 'programming': true → [java, programming]
    Add 'tutorial': true → [java, tutorial, programming]
    Add 'java' again: false → [java, tutorial, programming]
    Duplicate ignored!
    
    With more tags: [coding, java, beginner, tutorial, programming]
    
    === Blog Post Tags ===
    Total unique tags: 5
    Tags: [coding, java, beginner, tutorial, programming]
    
    === Formatted ===
  2. for (String tag : tags)

    pass 1 of 5
    39System.out.println("\n=== Formatted ===");40for (String tagcoding : tags[coding, java, beginner, tutorial, programming]) {41    System.out.print("#" + tagcoding + " ");42}
    output#coding 
    All 5 passes — pass 1 is the card above
    passtag
    1coding
    2java
    3beginner
    4tutorial
    5programming
  3. System.out.println();

    42    }43    System.out.println();44}

add() returns false if element already exists. Set stays unique.

HashSet Unordered collection of unique elements. O(1) add, remove, contains.

Fast membership check

Test if an item is in the set.

currentUser
CheckMembership.java
Replay: real traced execution (multi-file project)
import java.util.HashSet;
import java.util.Arrays;

public class CheckMembership {
    public static void main(String[] args) {
        // Create an allowlist of premium users
        HashSet<String> premiumUsers = new HashSet<>(Arrays.asList(
            "alice", "bob", "carol", "david"
        ));

        System.out.println("=== Premium Membership ===");
        System.out.println("Premium users: " + premiumUsers);

        // Check if user has access
        String currentUser = "bob";

        System.out.println("\n=== Access Check ===");
        System.out.println("User: " + currentUser);

        if (premiumUsers.contains(currentUser)) {
            System.out.println("✓ Premium access granted!");
            System.out.println("Welcome to exclusive content.");
        } else {
            System.out.println("✗ Not a premium user.");
            System.out.println("Upgrade to access premium features!");
        }

        // Blocked users check
        HashSet<String> blockedUsers = new HashSet<>(Arrays.asList(
            "spammer", "troll", "eve"
        ));

        System.out.println("\n=== Security Check ===");
        if (blockedUsers.contains(currentUser)) {
            System.out.println("⛔ User is blocked!");
        } else {
            System.out.println("✓ User is not blocked.");
        }

        // Check multiple users
        System.out.println("\n=== Batch Check ===");
        String[] usersToCheck = {"alice", "eve", "bob", "frank"};

        for (String user : usersToCheck) {
            String status = premiumUsers.contains(user) ? "Premium" : "Regular";
            System.out.println(user + ": " + status);
        }
    }
}
import java.util.HashSet;
import java.util.Arrays;

public class CheckMembership {
    public static void main(String[] args) {
        // Create an allowlist of premium users
        HashSet<String> premiumUsers = new HashSet<>(Arrays.asList(
            "alice", "bob", "carol", "david"
        ));

        System.out.println("=== Premium Membership ===");
        System.out.println("Premium users: " + premiumUsers);

        // Check if user has access
        String currentUser = "eve";

        System.out.println("\n=== Access Check ===");
        System.out.println("User: " + currentUser);

        if (premiumUsers.contains(currentUser)) {
            System.out.println("✓ Premium access granted!");
            System.out.println("Welcome to exclusive content.");
        } else {
            System.out.println("✗ Not a premium user.");
            System.out.println("Upgrade to access premium features!");
        }

        // Blocked users check
        HashSet<String> blockedUsers = new HashSet<>(Arrays.asList(
            "spammer", "troll", "eve"
        ));

        System.out.println("\n=== Security Check ===");
        if (blockedUsers.contains(currentUser)) {
            System.out.println("⛔ User is blocked!");
        } else {
            System.out.println("✓ User is not blocked.");
        }

        // Check multiple users
        System.out.println("\n=== Batch Check ===");
        String[] usersToCheck = {"alice", "eve", "bob", "frank"};

        for (String user : usersToCheck) {
            String status = premiumUsers.contains(user) ? "Premium" : "Regular";
            System.out.println(user + ": " + status);
        }
    }
}
  1. premiumUsers ← [carol, bob, alice, david], currentUser ← bob

    5public class CheckMembership {6    public static void main(String[] args) {7        // Create an allowlist of premium users  //#?allowlist8        HashSet<String> premiumUsers→ [carol, bob, alice, david] = new HashSet<>(Arrays.asList(9            "alice", "bob", "carol", "david"10        ));11        12        System.out.println("=== Premium Membership ===");13        System.out.println("Premium users: " + premiumUsers[carol, bob, alice, david]);14        15        // Check if user has access  //#?contains16        String currentUser→ bob = "bob";  //@var=_,eve17        18        System.out.println("\n=== Access Check ===");19        System.out.println("User: " + currentUserbob);
    output=== Premium Membership ===
    Premium users: [carol, bob, alice, david]
    
    === Access Check ===
    User: bob
  2. if (premiumUsers.contains(currentUser))

    21if (premiumUsers.contains(currentUserbob)) {22    System.out.println("✓ Premium access granted!");23    System.out.println("Welcome to exclusive content.");24} else {
    output✓ Premium access granted!
    Welcome to exclusive content.
  3. blockedUsers ← [spammer, eve, troll]

    29// Blocked users check30HashSet<String> blockedUsers→ [spammer, eve, troll] = new HashSet<>(Arrays.asList(  //@var=!,_31    "spammer", "troll", "eve"32));3334System.out.println("\n=== Security Check ===");  //@var=!,_35if (blockedUsers.contains(currentUser)) {  //@var=!,_
    output
    === Security Check ===
  4. else

    36    System.out.println("⛔ User is blocked!");  //@var=!,_37} else {  //@var=!,_38    System.out.println("✓ User is not blocked.");  //@var=!,_39}  //@var=!,_
    output✓ User is not blocked.
  5. String[] usersToCheck = {"alice", "eve", "bob", "frank"};

    41// Check multiple users42System.out.println("\n=== Batch Check ===");43String[] usersToCheck = {"alice", "eve", "bob", "frank"};
    output
    === Batch Check ===
  6. status ← Premium

    pass 1 of 4
    45for (String useralice : usersToCheck) {46    String status→ Premium = premiumUsers.contains(useralice) ? "Premium" : "Regular";47    System.out.println(useralice + ": " + statusPremium);48}
    outputalice: Premium
    All 4 passes — pass 1 is the card above
    passuserstatus
    1alicePremium
    2eveRegular
    3bobPremium
    4frankRegular
  1. premiumUsers ← [carol, bob, alice, david], currentUser ← eve

    4public class CheckMembership {5    public static void main(String[] args) {6        // Create an allowlist of premium users7        HashSet<String> premiumUsers→ [carol, bob, alice, david] = new HashSet<>(Arrays.asList(8            "alice", "bob", "carol", "david"9        ));10        11        System.out.println("=== Premium Membership ===");12        System.out.println("Premium users: " + premiumUsers[carol, bob, alice, david]);13        14        // Check if user has access15        String currentUser→ eve = "eve";16        17        System.out.println("\n=== Access Check ===");18        System.out.println("User: " + currentUsereve);
    output=== Premium Membership ===
    Premium users: [carol, bob, alice, david]
    
    === Access Check ===
    User: eve
  2. else

    22    System.out.println("Welcome to exclusive content.");23} else {24    System.out.println("✗ Not a premium user.");25    System.out.println("Upgrade to access premium features!");26}
    output✗ Not a premium user.
    Upgrade to access premium features!
  3. blockedUsers ← [spammer, eve, troll]

    28// Blocked users check29HashSet<String> blockedUsers→ [spammer, eve, troll] = new HashSet<>(Arrays.asList(30    "spammer", "troll", "eve"31));3233System.out.println("\n=== Security Check ===");34if (blockedUsers.contains(currentUser)) {
    output
    === Security Check ===
  4. if (blockedUsers.contains(currentUser))

    33System.out.println("\n=== Security Check ===");34if (blockedUsers.contains(currentUsereve)) {35    System.out.println("⛔ User is blocked!");36} else {
    output⛔ User is blocked!
  5. String[] usersToCheck = {"alice", "eve", "bob", "frank"};

    40// Check multiple users41System.out.println("\n=== Batch Check ===");42String[] usersToCheck = {"alice", "eve", "bob", "frank"};
    output
    === Batch Check ===
  6. status ← Premium

    pass 1 of 4
    44for (String useralice : usersToCheck) {45    String status→ Premium = premiumUsers.contains(useralice) ? "Premium" : "Regular";46    System.out.println(useralice + ": " + statusPremium);47}
    outputalice: Premium
    All 4 passes — pass 1 is the card above
    passuserstatus
    1alicePremium
    2eveRegular
    3bobPremium
    4frankRegular

contains() is O(1) - much faster than ArrayList's O(n) search.

Remove an item

Remove elements from the set.

RemoveItem.java
Replay: real traced execution (multi-file project)
import java.util.HashSet;
import java.util.Arrays;

public class RemoveItem {
    public static void main(String[] args) {
        HashSet<String> cart = new HashSet<>(Arrays.asList(
            "Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"
        ));

        System.out.println("=== Shopping Cart ===");
        System.out.println("Items: " + cart);
        System.out.println("Count: " + cart.size());

        // Remove an item
        String toRemove = "Mouse";
        boolean removed = cart.remove(toRemove);

        System.out.println("\n=== Removing Item ===");
        System.out.println("Remove '" + toRemove + "': " + removed);
        System.out.println("Cart: " + cart);

        // Try to remove non-existent item
        String notInCart = "Tablet";
        removed = cart.remove(notInCart);
        System.out.println("\nRemove '" + notInCart + "': " + removed);
        System.out.println("(Item wasn't in cart, so nothing changed)");

        // Remove more items
        cart.remove("Keyboard");
        cart.remove("Monitor");
        System.out.println("\nAfter more removals: " + cart);

        // Clear all
        System.out.println("\n=== Clearing Cart ===");
        System.out.println("Before clear: " + cart.size() + " items");
        cart.clear();
        System.out.println("After clear: " + cart.size() + " items");
        System.out.println("Cart is empty: " + cart.isEmpty());

        System.out.println("\n=== Final Cart ===");
        System.out.println("Items: " + cart);
        System.out.println("Count: " + cart.size());
    }
}
  1. cart ← [Headphones, Laptop, Monitor, Mouse, Keyboard], toRemove ← Mouse

    5public class RemoveItem {6    public static void main(String[] args) {7        HashSet<String> cart→ [Headphones, Laptop, Monitor, Mouse, Keyboard] = new HashSet<>(Arrays.asList(8            "Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"9        ));10        11        System.out.println("=== Shopping Cart ===");12        System.out.println("Items: " + cart[Headphones, Laptop, Monitor, Mouse, Keyboard]);13        System.out.println("Count: " + cart.size());14        15        // Remove an item  //#?remove16        String toRemove→ Mouse = "Mouse";17        boolean removed→ true = cart.remove(toRemoveMouse);18        19        System.out.println("\n=== Removing Item ===");20        System.out.println("Remove '" + toRemoveMouse + "': " + removedtrue);21        System.out.println("Cart: " + cart[Headphones, Laptop, Monitor, Keyboard]);22        23        // Try to remove non-existent item24        String notInCart→ Tablet = "Tablet";25        removed→ false = cart.remove(notInCartTablet);26        System.out.println("\nRemove '" + notInCartTablet + "': " + removedfalse);27        System.out.println("(Item wasn't in cart, so nothing changed)");28        29        // Remove more items30        cart.remove("Keyboard");  //@var=_,!31        cart.remove("Monitor");   //@var=_,!32        System.out.println("\nAfter more removals: " + cart[Headphones, Laptop]);  //@var=_,!33        34        // Clear all  //#?clear  //@var=!,_35        System.out.println("\n=== Clearing Cart ===");  //@var=!,_36        System.out.println("Before clear: " + cart.size() + " items");  //@var=!,_37        cart.clear();  //@var=!,_38        System.out.println("After clear: " + cart.size() + " items");  //@var=!,_39        System.out.println("Cart is empty: " + cart.isEmpty());  //@var=!,_40        41        System.out.println("\n=== Final Cart ===");42        System.out.println("Items: " + cart[]);43        System.out.println("Count: " + cart.size());44    }
    output=== Shopping Cart ===
    Items: [Headphones, Laptop, Monitor, Mouse, Keyboard]
    Count: 5
    
    === Removing Item ===
    Remove 'Mouse': true
    Cart: [Headphones, Laptop, Monitor, Keyboard]
    
    Remove 'Tablet': false
    (Item wasn't in cart, so nothing changed)
    
    After more removals: [Headphones, Laptop]
    
    === Clearing Cart ===
    Before clear: 2 items
    After clear: 0 items
    Cart is empty: true
    
    === Final Cart ===
    Items: []
    Count: 0

remove() returns true if element was present, false otherwise.

Combine two sets

Create a union of two sets.

SetUnion.java
Replay: real traced execution (multi-file project)
import java.util.HashSet;
import java.util.Arrays;

public class SetUnion {
    public static void main(String[] args) {
        // Two teams' skill sets
        HashSet<String> teamA = new HashSet<>(Arrays.asList(
            "Java", "Python", "SQL", "Git"
        ));

        HashSet<String> teamB = new HashSet<>(Arrays.asList(
            "JavaScript", "Python", "CSS", "Git"
        ));

        System.out.println("=== Team Skills ===");
        System.out.println("Team A: " + teamA);
        System.out.println("Team B: " + teamB);

        // Union: All skills combined
        HashSet<String> allSkills = new HashSet<>(teamA);  // Copy first
        allSkills.addAll(teamB);  // Add all from second

        System.out.println("\n=== Union (All Skills) ===");
        System.out.println("Combined: " + allSkills);
        System.out.println("(Duplicates automatically removed)");

        // Count unique skills
        System.out.println("\n=== Statistics ===");
        System.out.println("Team A skills: " + teamA.size());
        System.out.println("Team B skills: " + teamB.size());
        System.out.println("Unique combined: " + allSkills.size());
        System.out.println("Overlap count: " +
            (teamA.size() + teamB.size() - allSkills.size()));

        // Practical example: Merge user permissions
        System.out.println("\n=== Permission Merge ===");

        HashSet<String> basicPerms = new HashSet<>(Arrays.asList(
            "read", "comment"
        ));

        HashSet<String> editorPerms = new HashSet<>(Arrays.asList(
            "read", "write", "edit", "comment"
        ));

        HashSet<String> adminPerms = new HashSet<>(Arrays.asList(
            "read", "write", "edit", "delete", "manage"
        ));

        // Build editor permissions (basic + editor)
        HashSet<String> fullEditorPerms = new HashSet<>(basicPerms);
        fullEditorPerms.addAll(editorPerms);
        System.out.println("Editor has: " + fullEditorPerms);

        // Build admin permissions (all combined)
        HashSet<String> fullAdminPerms = new HashSet<>(basicPerms);
        fullAdminPerms.addAll(editorPerms);
        fullAdminPerms.addAll(adminPerms);
        System.out.println("Admin has: " + fullAdminPerms);
    }
}
  1. teamA ← [Java, Git, Python, SQL], teamB ← [CSS, Git, JavaScript, Python]

    4public class SetUnion {5    public static void main(String[] args) {6        // Two teams' skill sets7        HashSet<String> teamA→ [Java, Git, Python, SQL] = new HashSet<>(Arrays.asList(8            "Java", "Python", "SQL", "Git"9        ));10        11        HashSet<String> teamB→ [CSS, Git, JavaScript, Python] = new HashSet<>(Arrays.asList(12            "JavaScript", "Python", "CSS", "Git"13        ));14        15        System.out.println("=== Team Skills ===");16        System.out.println("Team A: " + teamA[Java, Git, Python, SQL]);17        System.out.println("Team B: " + teamB[CSS, Git, JavaScript, Python]);18        19        // Union: All skills combined  //#?union20        HashSet<String> allSkills→ [Java, Git, Python, SQL] = new HashSet<>(teamA);  // Copy first21        allSkills.addAll(teamB[CSS, Git, JavaScript, Python]);  // Add all from second22        23        System.out.println("\n=== Union (All Skills) ===");24        System.out.println("Combined: " + allSkills[Java, CSS, Git, JavaScript, Python, SQL]);25        System.out.println("(Duplicates automatically removed)");26        27        // Count unique skills28        System.out.println("\n=== Statistics ===");29        System.out.println("Team A skills: " + teamA.size());30        System.out.println("Team B skills: " + teamB.size());31        System.out.println("Unique combined: " + allSkills.size());32        System.out.println("Overlap count: " + 33            (teamA.size() + teamB.size() - allSkills.size()));34        35        // Practical example: Merge user permissions36        System.out.println("\n=== Permission Merge ===");37        38        HashSet<String> basicPerms→ [read, comment] = new HashSet<>(Arrays.asList(39            "read", "comment"40        ));41        42        HashSet<String> editorPerms→ [read, edit, comment, write] = new HashSet<>(Arrays.asList(43            "read", "write", "edit", "comment"44        ));45        46        HashSet<String> adminPerms→ [read, edit, write, delete, manage] = new HashSet<>(Arrays.asList(47            "read", "write", "edit", "delete", "manage"48        ));49        50        // Build editor permissions (basic + editor)51        HashSet<String> fullEditorPerms→ [read, comment] = new HashSet<>(basicPerms);52        fullEditorPerms.addAll(editorPerms[read, edit, comment, write]);53        System.out.println("Editor has: " + fullEditorPerms[read, edit, comment, write]);54        55        // Build admin permissions (all combined)56        HashSet<String> fullAdminPerms→ [read, comment] = new HashSet<>(basicPerms);57        fullAdminPerms.addAll(editorPerms[read, edit, comment, write]);58        fullAdminPerms.addAll(adminPerms[read, edit, write, delete, manage]);59        System.out.println("Admin has: " + fullAdminPerms[read, edit, comment, write, delete, manage]);60    }
    output=== Team Skills ===
    Team A: [Java, Git, Python, SQL]
    Team B: [CSS, Git, JavaScript, Python]
    
    === Union (All Skills) ===
    Combined: [Java, CSS, Git, JavaScript, Python, SQL]
    (Duplicates automatically removed)
    
    === Statistics ===
    Team A skills: 4
    Team B skills: 4
    Unique combined: 6
    Overlap count: 2
    
    === Permission Merge ===
    Editor has: [read, edit, comment, write]
    Admin has: [read, edit, comment, write, delete, manage]

addAll() adds all elements from another collection. Duplicates ignored.

union Combine sets: `set1.addAll(set2)`. Result has all unique elements.

Remove duplicates from list

Convert a list to set to eliminate duplicates.

RemoveDuplicates.java
Replay: real traced execution (multi-file project)
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Arrays;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // List with duplicate entries
        ArrayList<String> emails = new ArrayList<>(Arrays.asList(
            "alice@example.com",
            "bob@example.com",
            "alice@example.com",  // duplicate
            "carol@example.com",
            "bob@example.com",    // duplicate
            "david@example.com",
            "alice@example.com"   // duplicate
        ));

        System.out.println("=== Email List (with duplicates) ===");
        System.out.println("Emails: " + emails);
        System.out.println("Count: " + emails.size());

        // Remove duplicates using HashSet
        HashSet<String> uniqueEmails = new HashSet<>(emails);

        System.out.println("\n=== After Removing Duplicates ===");
        System.out.println("Unique: " + uniqueEmails);
        System.out.println("Count: " + uniqueEmails.size());
        System.out.println("Removed " + (emails.size() - uniqueEmails.size()) + " duplicates");

        // Convert back to ArrayList if needed
        ArrayList<String> cleanedList = new ArrayList<>(uniqueEmails);
        System.out.println("\nAs ArrayList: " + cleanedList);

        // Preserve original order using LinkedHashSet
        System.out.println("\n=== Preserving Order ===");
        java.util.LinkedHashSet<String> orderedUnique =
            new java.util.LinkedHashSet<>(emails);
        System.out.println("LinkedHashSet: " + orderedUnique);
        System.out.println("(Maintains insertion order!)");

        // Count duplicates
        System.out.println("\n=== Duplicate Analysis ===");
        java.util.HashMap<String, Integer> counts = new java.util.HashMap<>();
        for (String email : emails) {
            counts.put(email, counts.getOrDefault(email, 0) + 1);
        }

        for (String email : counts.keySet()) {
            int count = counts.get(email);
            if (count > 1) {
                System.out.println(email + " appeared " + count + " times");
            }
        }
    }
}
  1. emails ← [alice@example.com, bob@example.com, alice@example.com, carol@example.com, bob@example.com, david@example.com, alice@example.com]

    6public class RemoveDuplicates {7    public static void main(String[] args) {8        // List with duplicate entries9        ArrayList<String> emails→ [alice@example.com, bob@example.com, alice@example.com, carol@example.com, bob@example.com, david@example.com, alice@example.com] = new ArrayList<>(Arrays.asList(10            "alice@example.com",11            "bob@example.com",12            "alice@example.com",  // duplicate13            "carol@example.com",14            "bob@example.com",    // duplicate15            "david@example.com",16            "alice@example.com"   // duplicate17        ));18        19        System.out.println("=== Email List (with duplicates) ===");20        System.out.println("Emails: " + emails[alice@example.com, bob@example.com, alice@example.com, carol@example.com, bob@example.com, david@example.com, alice@example.com]);21        System.out.println("Count: " + emails.size());22        23        // Remove duplicates using HashSet  //#?dedup24        HashSet<String> uniqueEmails→ [david@example.com, alice@example.com, carol@example.com, bob@example.com] = new HashSet<>(emails);25        26        System.out.println("\n=== After Removing Duplicates ===");27        System.out.println("Unique: " + uniqueEmails[david@example.com, alice@example.com, carol@example.com, bob@example.com]);28        System.out.println("Count: " + uniqueEmails.size());29        System.out.println("Removed " + (emails.size() - uniqueEmails.size()) + " duplicates");30        31        // Convert back to ArrayList if needed  //#?convert32        ArrayList<String> cleanedList→ [david@example.com, alice@example.com, carol@example.com, bob@example.com] = new ArrayList<>(uniqueEmails);33        System.out.println("\nAs ArrayList: " + cleanedList[david@example.com, alice@example.com, carol@example.com, bob@example.com]);34        35        // Preserve original order using LinkedHashSet  //@var=!,_36        System.out.println("\n=== Preserving Order ===");37        java.util.LinkedHashSet<String> orderedUnique→ [alice@example.com, bob@example.com, carol@example.com, david@example.com] = 38            new java.util.LinkedHashSet<>(emails);  //?linked39        System.out.println("LinkedHashSet: " + orderedUnique[alice@example.com, bob@example.com, carol@example.com, david@example.com]);40        System.out.println("(Maintains insertion order!)");41        42        // Count duplicates43        System.out.println("\n=== Duplicate Analysis ===");44        java.util.HashMap<String, Integer> counts→ {} = new java.util.HashMap<>();45        for (String email : emails) {
    output=== Email List (with duplicates) ===
    Emails: [alice@example.com, bob@example.com, alice@example.com, carol@example.com, bob@example.com, david@example.com, alice@example.com]
    Count: 7
    
    === After Removing Duplicates ===
    Unique: [david@example.com, alice@example.com, carol@example.com, bob@example.com]
    Count: 4
    Removed 3 duplicates
    
    As ArrayList: [david@example.com, alice@example.com, carol@example.com, bob@example.com]
    
    === Preserving Order ===
    LinkedHashSet: [alice@example.com, bob@example.com, carol@example.com, david@example.com]
    (Maintains insertion order!)
    
    === Duplicate Analysis ===
  2. for (String email : emails)

    pass 1 of 7
    44java.util.HashMap<String, Integer> counts = new java.util.HashMap<>();45for (String emailalice@example.com : emails[alice@example.com, bob@example.com, alice@example.com, carol@example.com, bob@example.com, david@example.com, alice@example.com]) {46    counts.put(emailalice@example.com, counts.getOrDefault(email, 0) + 1);47}
    All 7 passes — pass 1 is the card above
    passemailcount
    1alice@example.com
    2bob@example.com
    3alice@example.com
    4carol@example.com
    5bob@example.com
    6david@example.com
    7alice@example.com3
  3. count ← 1

    pass 1 of 4
    49for (String emaildavid@example.com : counts.keySet()) {50    int count→ 1 = counts.get(emaildavid@example.com);51    if (count > 1) {
    All 4 passes — pass 1 is the card above
    passemailcount
    1david@example.com1
    2alice@example.com3
    3carol@example.com1
    4bob@example.com2
  4. if (count > 1)

    pass 1 of 2
    50int count = counts.get(email);51if (count3 > 1) {52    System.out.println(emailalice@example.com + " appeared " + count3 + " times");53}
    outputalice@example.com appeared 3 times
  5. if (count > 1)

    pass 2 of 2
    50int count = counts.get(email);51if (count2 > 1) {52    System.out.println(emailbob@example.com + " appeared " + count2 + " times");53}
    outputbob@example.com appeared 2 times

new HashSet<>(list) creates set from list, removing duplicates.

Exercise: SetOperations.java

Explore intersection, difference, and other set operations