Java:Java HashSet: Deduplication and Unique Sets
Java•Sets

Java HashSet: Deduplication and Unique Sets

Learn how HashSet eliminates duplicate elements and delivers O(1) membership testing with contains().

Syntax

HashSet<String> set = new HashSet<>(); set.add("A"); boolean hasA = set.contains("A");

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
HashSet<T>Set CollectionBacking hash table storing unique items.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

import java.util.HashSet;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Automatic deduplication of input list
        HashSet<String> allowedRoles = new HashSet<>(
            Arrays.asList("ADMIN", "DEVELOPER", "REVIEWER", "ADMIN")
        );

        System.out.println("Unique Roles: " + allowedRoles);
        System.out.println("Total Roles:  " + allowedRoles.size());

        // Fast O(1) membership check
        System.out.println("Contains ADMIN?    " + allowedRoles.contains("ADMIN"));
        System.out.println("Contains GUEST?    " + allowedRoles.contains("GUEST"));
    }
}
Expected Output:
Unique Roles: [REVIEWER, DEVELOPER, ADMIN]
Total Roles:  3
Contains ADMIN?    true
Contains GUEST?    false

How It Works: Step-by-Step

  • Lines 6-8: Deduplicates input list ("ADMIN" added twice, stored once).
  • Lines 14-15: contains() performs fast hash table lookup.

Key Concepts

  • HashSet allows at most one null element and guarantees uniqueness.
  • Custom objects in HashSet must properly override equals() and hashCode().
  • TreeSet stores elements in natural sorted order.

Common Mistake: Using custom class in HashSet without overriding equals() and hashCode()

Without hashCode/equals, distinct instances with identical fields are treated as different objects.

❌ Incorrect
class User { int id; } // Duplicate User objects will both be stored!
✅ Correct
// Override equals() and hashCode() on id field

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler