Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
3. Core APIs & I/O
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

27. HashSets: The Art of Uniqueness

Filtering out duplicates automatically using Set math.

Feb 22, 20264 views0 likes0 fires
18px

[!NOTE] Sometimes you don't care about order, and you don't even care about key-value mapping. You just have a massive influx of data and you need to mathematically guarantee that every single item is completely unique.

If you use an ArrayList, adding "BMW" ten times will add ten distinct "BMW" entries into the list. If you use a HashSet, it evaluates the data, realizes "BMW" already exists, and silently ignores the other nine additions.

Use Cases

Imagine you are parsing a text file containing 10,000 email addresses, trying to build a spam-marketing list. If John signed up 5 times, you don't want to email him 5 times. By dumping the entire list into a HashSet, all duplicates are automatically stripped away in milliseconds!

Syntax

The syntax is identical to an ArrayList, but with the magical uniqueness guarantee natively built-in.

import java.util.HashSet;

public class Main {
  public static void main(String[] args) {
    HashSet<String> cars = new HashSet<String>();
    
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("BMW"); // Ignored!
    cars.add("Mazda");
    cars.add("Volvo"); // Ignored!
    
    // Outputs 4, not 6!
    System.out.println("Total Unique Cars: " + cars.size());
    
    // HashSets use .contains() which is incredibly fast!
    if(cars.contains("Mazda")) {
        System.out.println("Mazda is in the unique Set.");
    }
  }
}

[!CAUTION] No Concept of Indexing! A HashSet does not use indices. You cannot ask a HashSet for .get(2). The items are mathematically scattered in memory, and the "order" they are stored in is basically random. If you iterate through a HashSet, do not expect it to print in the order you added the items!

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

easyJava
Quiz: HashSets
11 questions5 min

Continue Learning

28. Iterator: Safe Collection Traversal

Advanced
9 min

29. Wrapper Classes & Autoboxing

Intermediate
8 min

30. Basic File I/O

Intermediate
14 min
Lesson 7 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
26. HashMaps: Key-Value Architecture
Next in 3. Core APIs & I/O
28. Iterator: Safe Collection Traversal
← Back to Java Programming: From Zero to Enterprise
Back to Java Programming: From Zero to EnterpriseAll Categories