Sets

Back

Loading concept...

πŸŽ’ The Backpack of Unique Treasures: Java Sets

Imagine you have a magical backpack. This backpack has a special rule: you can only keep ONE of each treasure. If you try to put in a second shiny red marble, the backpack just ignores it! That’s exactly how Java Sets work.


🌟 What is a Set?

A Set is like a collection box that hates duplicates. It only keeps unique items.

Real Life Examples:

  • 🎟️ A guest list at a party (each person can only be listed once!)
  • πŸ”’ Unique lottery numbers drawn
  • πŸ“§ Email addresses you’ve signed up with (no repeats allowed)
// Creating a Set is simple!
Set<String> guests = new HashSet<>();
guests.add("Alice");
guests.add("Bob");
guests.add("Alice"); // Ignored! Alice is already there
// Result: [Alice, Bob]

πŸ“œ The Set Interface: The Rule Book

The Set Interface is like the rulebook that all Sets must follow. It says:

β€œNo duplicates allowed. Period.”

Key Powers of Set Interface:

Power What It Does
add(item) Adds if not duplicate
remove(item) Removes the item
contains(item) Checks if item exists
size() Counts unique items
isEmpty() Checks if empty
Set<Integer> numbers = new HashSet<>();
numbers.add(5);
numbers.add(10);
numbers.add(5); // Nope! Already have 5

System.out.println(numbers.size()); // 2
System.out.println(numbers.contains(5)); // true

🏠 HashSet: The Messy but Fast Friend

HashSet is like a friend who throws items into a bag super fast, but doesn’t care about order. Want to find something? They’ll find it instantly!

🎯 Key Points:

  • ⚑ Super Fast - Adding, removing, finding = instant
  • 🎲 No Order - Items come out in random order
  • βœ… Allows ONE null - You can have one empty spot
  • πŸ”§ Uses hashing (like magic filing cabinets)
Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.add("Red"); // Ignored!

// Printing might show: [Blue, Red, Green]
// Order is unpredictable!

🧠 How Does Hashing Work?

Imagine 10 buckets numbered 0-9. Each item gets a β€œhome number” based on its value. Finding it later? Just go to that bucket!

graph TD A["Item: Apple"] -->|Hash = 3| B["Bucket 3"] C["Item: Banana"] -->|Hash = 7| D["Bucket 7"] E["Item: Cherry"] -->|Hash = 3| B style B fill:#90EE90 style D fill:#90EE90

πŸ”— LinkedHashSet: The Organized Friend

LinkedHashSet is like HashSet’s neat sibling. It’s still fast, but it remembers the order you added things!

🎯 Key Points:

  • πŸ“‹ Maintains Insertion Order - First in, first out
  • ⚑ Still Fast - Almost as quick as HashSet
  • πŸ”— Uses a linked list behind the scenes
Set<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Always prints: [Apple, Banana, Cherry]
// Order preserved!

πŸ†š HashSet vs LinkedHashSet

Feature HashSet LinkedHashSet
Speed Fastest Slightly slower
Order Random Insertion order
Memory Less Slightly more

🌳 TreeSet: The Alphabetical Wizard

TreeSet is like a librarian who automatically organizes everything in order. Numbers go small to big. Words go A to Z!

🎯 Key Points:

  • πŸ“Š Sorted Order - Always organized
  • 🚫 No null allowed - Hates empty spots
  • 🌲 Uses a tree structure (Red-Black Tree)
Set<Integer> scores = new TreeSet<>();
scores.add(75);
scores.add(50);
scores.add(100);
scores.add(25);

// Always prints: [25, 50, 75, 100]
// Automatically sorted!

πŸ”€ Sorting Strings

Set<String> names = new TreeSet<>();
names.add("Zoe");
names.add("Alice");
names.add("Mike");

// Output: [Alice, Mike, Zoe]
// Alphabetical order!
graph TD A["75"] --> B["50"] A --> C["100"] B --> D["25"] style A fill:#FFD700 style B fill:#87CEEB style C fill:#87CEEB style D fill:#90EE90

πŸ“Š SortedSet: The Sorting Contract

SortedSet is an interface (rulebook) that guarantees elements are always sorted. TreeSet follows this rulebook!

🎁 Special Powers of SortedSet:

Method What It Does Example
first() Gets smallest 25
last() Gets largest 100
headSet(x) All items < x Items before x
tailSet(x) All items >= x Items from x onwards
SortedSet<Integer> nums = new TreeSet<>();
nums.add(10);
nums.add(30);
nums.add(20);
nums.add(40);

System.out.println(nums.first()); // 10
System.out.println(nums.last());  // 40
System.out.println(nums.headSet(25)); // [10, 20]
System.out.println(nums.tailSet(25)); // [30, 40]

🧭 NavigableSet: The GPS of Sets

NavigableSet extends SortedSet with even MORE navigation powers. It’s like having GPS for your sorted collection!

🎯 Extra Navigation Powers:

Method Description
lower(x) Greatest element < x
floor(x) Greatest element <= x
ceiling(x) Smallest element >= x
higher(x) Smallest element > x
pollFirst() Remove & return smallest
pollLast() Remove & return largest
descendingSet() Reverse order view
NavigableSet<Integer> nums = new TreeSet<>();
nums.add(10);
nums.add(20);
nums.add(30);
nums.add(40);

System.out.println(nums.lower(25));   // 20
System.out.println(nums.floor(30));   // 30
System.out.println(nums.ceiling(25)); // 30
System.out.println(nums.higher(25));  // 30

πŸ”„ Reverse Order

NavigableSet<Integer> reversed = nums.descendingSet();
// Shows: [40, 30, 20, 10]

🎨 When to Use Which Set?

graph TD A["Need a Set?"] --> B{Need Order?} B -->|No Order| C["HashSet ⚑"] B -->|Yes| D{What Order?} D -->|Insertion Order| E["LinkedHashSet πŸ”—"] D -->|Sorted Order| F["TreeSet 🌳"] style C fill:#90EE90 style E fill:#87CEEB style F fill:#FFD700

Quick Decision Guide:

Scenario Best Choice
Just want unique items, fast HashSet
Keep order I added them LinkedHashSet
Auto-sort, find min/max TreeSet
Navigate sorted data TreeSet (NavigableSet)

πŸŽ“ Complete Example: Student ID System

Let’s build a student ID tracker using all three Sets!

import java.util.*;

public class StudentDemo {
    public static void main(String[] args) {
        // HashSet: Fast lookup
        Set<Integer> hashIds = new HashSet<>();
        hashIds.add(101);
        hashIds.add(103);
        hashIds.add(102);
        System.out.println("HashSet: " + hashIds);
        // Random: [101, 102, 103] or any order

        // LinkedHashSet: Remember order
        Set<Integer> linkedIds = new LinkedHashSet<>();
        linkedIds.add(101);
        linkedIds.add(103);
        linkedIds.add(102);
        System.out.println("LinkedHashSet: " + linkedIds);
        // Ordered: [101, 103, 102]

        // TreeSet: Sorted always
        TreeSet<Integer> treeIds = new TreeSet<>();
        treeIds.add(101);
        treeIds.add(103);
        treeIds.add(102);
        System.out.println("TreeSet: " + treeIds);
        // Sorted: [101, 102, 103]

        // NavigableSet powers
        System.out.println("First: " + treeIds.first());
        System.out.println("Last: " + treeIds.last());
        System.out.println("Below 102: " + treeIds.lower(102));
    }
}

🌈 Remember This!

HashSet = Speed King πŸ‘‘ (no order)

LinkedHashSet = Memory Lane πŸ”— (insertion order)

TreeSet = Sorting Wizard πŸ§™ (always sorted)

SortedSet = The sorting rulebook πŸ“œ

NavigableSet = GPS navigation 🧭

Sets are your best friend when you want unique items. Choose the right one based on whether you need speed, order, or sorting!


πŸŽ‰ You Did It!

You now understand Java Sets! Remember the magical backpack that only keeps one of each treasure? That’s your Set. Whether you need:

  • ⚑ Raw speed β†’ HashSet
  • πŸ“‹ Order memory β†’ LinkedHashSet
  • πŸ“Š Auto-sorting β†’ TreeSet

You’ve got the right tool for every job. Happy coding! πŸš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.