☕ Java

Collections

Lesson 4 of 5 ~5 min

The Collections Framework provides data structures for storing and manipulating groups of objects. Instead of manually managing arrays with fixed sizes, collections let you dynamically add, remove, and search elements at runtime.

Java's collections are divided into two main categories: Lists (ordered sequences that allow duplicates) and Maps (key-value pairs that provide fast lookups). The framework includes generics, which let you specify what type of objects a collection holds.

ArrayList vs LinkedList

Working with ArrayList

The most commonly used collection is ArrayList. It grows dynamically as you add elements and provides fast access by index. Here's how to create, populate, and iterate through one.

Editor
Java
Output

Try it

Try adding more fruits, removing different ones, or printing a specific index with fruits.get(2).

HashMap

A HashMap stores data as key-value pairs. Each key maps to exactly one value. Keys must be unique — if you put a value with an existing key, the old value is replaced. HashMap provides very fast lookup by key.

import java.util.HashMap;

HashMap<String, Integer> scores = new HashMap<>();

scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 92);

System.out.println(scores);            // {Alice=95, Bob=87, Charlie=92}
System.out.println(scores.get("Alice")); // 95
System.out.println(scores.containsKey("Bob")); // true

scores.put("Alice", 98);  // Update Alice's score
System.out.println(scores.get("Alice")); // 98

Iterating through collections

Java provides several ways to loop through collections. The enhanced for loop (also called the "for-each" loop) is the most readable for simple iteration.

import java.util.ArrayList;

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

// Enhanced for loop (most common)
for (String color : colors) {
    System.out.println(color);
}

// Traditional for loop (when you need the index)
for (int i = 0; i < colors.size(); i++) {
    System.out.println(i + ": " + colors.get(i));
}

// Iterating a HashMap
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);

for (String name : ages.keySet()) {
    System.out.println(name + " is " + ages.get(name));
}

Generics basics

Generics let you specify the type of elements a collection holds. This provides type safety — the compiler catches errors if you try to add the wrong type of object. You use angle brackets <Type> to declare the generic type.

// ArrayList<String> — only String objects allowed
ArrayList<String> names = new ArrayList<>();
names.add("Alice");  // ✅ works
// names.add(42);    // ❌ compile error!

// ArrayList<Integer> — only Integer objects
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(42);     // ✅ works
// numbers.add("hi"); // ❌ compile error!

// Without generics, you'd get runtime ClassCastExceptions

Quiz

Which collection maintains insertion order and allows duplicates?
Challenge

Create an ArrayList of your five favorite foods. Use a for-each loop to print each one. Then use removeIf() to remove any food that starts with the letter "B" and print the updated list.