Java Collections – Baby Steps (JDK 1.8)

Welcome to Programmer’s Picnic! In this lesson, we take slow, easy baby steps into one of the most important parts of Java: The Collections Framework.


🌱 What Are Collections?

A Collection in Java is simply an object that can store multiple values. In real life, think of collections like:

Baby Step Rule: Arrays are fixed size. Collections grow and shrink automatically!

🌼 The Main Root Interfaces

Interface What it Represents
List Ordered collection β†’ allows duplicates (e.g., ArrayList)
Set No duplicates allowed (e.g., HashSet)
Queue First-in-first-out operations (e.g., LinkedList)
Map Stores key-value pairs (e.g., HashMap)

🌸 Baby Step 1 β€” Using ArrayList

ArrayList is the most common Java collection.

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        ArrayList&lt;String&gt; names = new ArrayList<>();

        names.add("Ram");
        names.add("Shyam");
        names.add("Geeta");

        System.out.println(names);
    }
}
ArrayList keeps elements in the order you add them.

🌸 Baby Step 2 β€” Looping Through a List

Enhanced For-Loop

for (String n : names) {
    System.out.println(n);
}

Java 1.8 forEach + Lambda

names.forEach(n -> System.out.println(n));

🌻 Baby Step 3 β€” Using HashSet

A Set removes duplicates automatically.

HashSet&lt;Integer&gt; set = new HashSet<>();

set.add(10);
set.add(20);
set.add(10);

System.out.println(set); // duplicate 10 removed
Important: HashSet does NOT guarantee order.

🌷 Baby Step 4 β€” Using HashMap

A map stores key β†’ value pairs.

HashMap&lt;String, Integer&gt; marks = new HashMap<>();

marks.put("Math", 95);
marks.put("English", 88);

System.out.println(marks.get("Math"));
Keys must be unique. Values may repeat.

🌼 Baby Step 5 β€” Iterating a Map

for (Map.Entry&lt;String, Integer&gt; e : marks.entrySet()) {
    System.out.println(e.getKey() + ": " + e.getValue());
}

Java 8 forEach (Lambda)

marks.forEach((k, v) -> 
    System.out.println(k + " = " + v)
);

πŸƒ Baby Step 6 β€” When to Use What?

Use This When You Need
ArrayList Order maintained, duplicates allowed
LinkedList Fast insert/delete
HashSet No duplicates
TreeSet Sorted elements
HashMap Key-value lookup
LinkedHashMap Map + maintains insertion order

🎯 Mini Quiz

1. Which collection maintains order and allows duplicates?
βœ” ArrayList

2. Which collection removes duplicates?
βœ” HashSet

3. Which one stores key-value pairs?
βœ” HashMap

🌟 Final Note

Mastering collections is the biggest stepping stone before streams, lambdas, and functional programming in Java 1.8.

Keep practicing β€” your foundation will become unshakeable.