Collection Utilities

Back

Loading concept...

🎒 The Magical Toolbox: Java Collection Utilities

Imagine you have a toy box full of different toys. Sometimes you want to look at each toy one by one. Sometimes you want to sort them by size. Sometimes you want to make sure nobody can add or remove toys. That’s exactly what Java Collection Utilities help you do!


🚶 Iterator and ListIterator: Your Collection Tour Guide

Think of an Iterator like a museum tour guide. The guide walks you through the museum, showing you one painting at a time. You can only go forward and the guide tells you when you’ve seen everything.

What is Iterator?

An Iterator is a helper that lets you visit each item in a collection one at a time.

List<String> toys = new ArrayList<>();
toys.add("Car");
toys.add("Doll");
toys.add("Ball");

Iterator<String> guide = toys.iterator();
while (guide.hasNext()) {
    String toy = guide.next();
    System.out.println(toy);
}

Key Methods:

  • hasNext() → “Is there another item to see?”
  • next() → “Show me the next item!”
  • remove() → “Take this item away”

ListIterator: The Advanced Guide

Now imagine a special tour guide who can walk both forward AND backward! That’s ListIterator.

List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Blue");
colors.add("Green");

ListIterator<String> superGuide =
    colors.listIterator();

// Go forward
while (superGuide.hasNext()) {
    System.out.println(superGuide.next());
}

// Now go backward!
while (superGuide.hasPrevious()) {
    System.out.println(superGuide.previous());
}

Extra Powers of ListIterator:

  • hasPrevious() → “Can I go back?”
  • previous() → “Show me the previous item!”
  • add() → “Insert a new item here!”
  • set() → “Replace current item!”

📦 Iterable Interface: The Promise to Be Walkable

When something is Iterable, it’s making a promise: “You can walk through me!”

Think of it like a nature trail with a clear path. If a trail is “walkable” (Iterable), you can follow it from start to end.

// Any class implementing Iterable
// can be used in a for-each loop!
for (String toy : toys) {
    System.out.println(toy);
}

The Iterable interface has just one method: iterator() which gives you your tour guide!

graph TD A["Iterable Interface"] --> B["iterator method"] B --> C["Returns Iterator"] C --> D["Walk through items"]

🎯 Iterator Behavior: The Rules of the Walk

Iterators follow strict rules, like a polite visitor in a museum:

Rule 1: One Direction Only (Iterator)

Regular Iterator only moves forward. Like reading a book from start to end.

Rule 2: No Cheating!

Once you pass an item, you can’t see it again with the same iterator.

Rule 3: Safe Removal

You can remove the current item using remove(), but only after calling next().

Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
    Integer num = it.next();
    if (num < 0) {
        it.remove(); // Remove negative numbers
    }
}

Rule 4: Fail-Fast Behavior

If someone else changes the collection while you’re walking through it, the iterator gets upset and throws a ConcurrentModificationException!


⚖️ Comparable Interface: Teaching Objects to Compare Themselves

Imagine you have toy soldiers. How do you line them up by height? Each soldier needs to know how to compare itself with others!

Comparable means: “I know how to compare myself to others like me.”

public class Student
    implements Comparable<Student> {

    String name;
    int age;

    @Override
    public int compareTo(Student other) {
        return this.age - other.age;
    }
}

The compareTo Rules:

  • Return negative → “I’m smaller!”
  • Return zero → “We’re equal!”
  • Return positive → “I’m bigger!”
// Now you can sort students!
List<Student> students = new ArrayList<>();
Collections.sort(students);

🎭 Comparator Interface: The External Judge

Sometimes you can’t change how an object compares itself. Or you want different ways to compare!

Enter Comparator: an external judge who decides who wins.

// Sort by name (alphabetically)
Comparator<Student> byName =
    (s1, s2) -> s1.name.compareTo(s2.name);

// Sort by age (youngest first)
Comparator<Student> byAge =
    (s1, s2) -> s1.age - s2.age;

// Use whichever you need!
Collections.sort(students, byName);
Collections.sort(students, byAge);

Comparable vs Comparator

Comparable Comparator
Object compares itself External judge compares
Only ONE way to sort MANY ways to sort
compareTo() method compare() method
In the class itself Separate class/lambda
graph TD A["Need to Sort Objects?"] A --> B{Can modify class?} B -->|Yes| C["Use Comparable"] B -->|No| D["Use Comparator"] A --> E{Need multiple sorts?} E -->|Yes| D E -->|No| C

🧰 Collections Utility Class: Your Swiss Army Knife

Collections (with an ‘s’!) is a class full of helper tools for working with collections. It’s like having a magical toolbox!

Sorting

List<Integer> nums = Arrays.asList(3, 1, 4, 1, 5);
Collections.sort(nums);
// Result: [1, 1, 3, 4, 5]

Reversing

Collections.reverse(nums);
// Result: [5, 4, 3, 1, 1]

Shuffling (Random Order)

Collections.shuffle(nums);
// Result: Random order!

Finding Max and Min

int biggest = Collections.max(nums);
int smallest = Collections.min(nums);

Binary Search

// List must be sorted first!
Collections.sort(nums);
int position = Collections.binarySearch(nums, 3);

Fill and Replace

Collections.fill(nums, 0);    // All become 0
Collections.replaceAll(nums, 1, 99);

📊 Collection Sorting: Putting Things in Order

Sorting is like organizing your bookshelf. You can organize by title, author, or size!

Natural Ordering (Comparable)

List<String> fruits = new ArrayList<>();
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Cherry");

Collections.sort(fruits);
// Result: [Apple, Banana, Cherry]

Custom Ordering (Comparator)

// Sort by length of word
Collections.sort(fruits,
    (a, b) -> a.length() - b.length());
// Result: [Apple, Cherry, Banana]

Reverse Order

Collections.sort(fruits,
    Collections.reverseOrder());
// Result: [Cherry, Banana, Apple]

Sorting Objects

// Using Comparator.comparing()
List<Student> students = getStudents();

students.sort(
    Comparator.comparing(s -> s.getName())
);

// Multiple criteria: by age, then by name
students.sort(
    Comparator.comparing(Student::getAge)
        .thenComparing(Student::getName)
);

🔒 Immutable Collections: The Untouchable Treasures

Imagine a museum display case with precious gems. You can look but you can never touch or change them!

Immutable means: “Cannot be changed after creation.”

Creating Immutable Lists

// Method 1: List.of()
List<String> gems = List.of("Ruby", "Diamond");

// Trying to add? ERROR!
gems.add("Emerald"); // Throws Exception!

Creating Immutable Sets

Set<Integer> luckyNumbers = Set.of(7, 11, 21);
// Cannot add or remove!

Creating Immutable Maps

Map<String, Integer> scores = Map.of(
    "Alice", 95,
    "Bob", 87
);
// Cannot change values!

Making Existing Collections Immutable

List<String> original = new ArrayList<>();
original.add("Cat");
original.add("Dog");

// Wrap in unmodifiable view
List<String> locked =
    Collections.unmodifiableList(original);

locked.add("Bird"); // Throws Exception!

Why Use Immutable Collections?

Benefit Explanation
Safety No accidental changes
Thread-Safe Safe to share between threads
Predictable Value never changes unexpectedly
Clear Intent Shows this data is constant
graph TD A["Immutable Collection"] A --> B["Cannot Add"] A --> C["Cannot Remove"] A --> D["Cannot Modify"] A --> E["Can Only Read"]

🎯 Quick Summary

Tool Purpose Key Thing to Remember
Iterator Walk forward through items Like a museum tour
ListIterator Walk forward AND backward For Lists only
Iterable Promise to be walkable Enables for-each
Comparable Self-comparison ONE natural order
Comparator External comparison MANY custom orders
Collections Utility toolbox sort, shuffle, max…
Immutable Read-only collections Safe & unchangeable

🌟 You Made It!

You now understand how to:

  • Walk through collections using Iterators
  • Make objects sortable with Comparable
  • Create custom sorting rules with Comparator
  • Use the powerful Collections utility class
  • Protect data with Immutable collections

These tools are like superpowers for managing your data. Now go practice and make them second nature! 🚀

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.