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.
A Collection in Java is simply an object that can store multiple values. In real life, think of collections like:
| 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) |
ArrayListArrayList is the most common Java collection.
import java.util.*;
public class Demo {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ram");
names.add("Shyam");
names.add("Geeta");
System.out.println(names);
}
}
for (String n : names) {
System.out.println(n);
}
names.forEach(n -> System.out.println(n));
HashSetA Set removes duplicates automatically.
HashSet<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10);
System.out.println(set); // duplicate 10 removed
HashMapA map stores key β value pairs.
HashMap<String, Integer> marks = new HashMap<>();
marks.put("Math", 95);
marks.put("English", 88);
System.out.println(marks.get("Math"));
for (Map.Entry<String, Integer> e : marks.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
marks.forEach((k, v) ->
System.out.println(k + " = " + v)
);
| 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 |
Mastering collections is the biggest stepping stone before streams, lambdas, and functional programming in Java 1.8.
Keep practicing β your foundation will become unshakeable.