🎯 What you will learn
- Use ArrayList for growing lists
- Use HashMap for key–value data
- Loop with for-each
👋 Let’s get started!
Arrays have a fixed size — but real apps grow! 📈 Java’s collections handle lists that grow and lookups by key, just like Python lists and dictionaries.
🪜 Step by step
1. 📋 ArrayList
Import it, then add(), get() and size().
import java.util.ArrayList;
ArrayList<String> songs = new ArrayList<>();
songs.add("Believer");
songs.add("Happy");
System.out.println(songs.get(0) + " / " + songs.size());
2. 🗝️ HashMap
put() a key and value, get() it back.
import java.util.HashMap;
HashMap<String, Integer> stock = new HashMap<>();
stock.put("apples", 12);
stock.put("pears", 4);
System.out.println(stock.get("apples"));
3. 🔁 for-each
Loop through every item easily.
for (String s : songs) {
System.out.println("♪ " + s);
}
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Word counter
String text = "the cat and the dog and the bird";
HashMap<String, Integer> counts = new HashMap<>();
for (String w : text.split(" ")) {
counts.put(w, counts.getOrDefault(w, 0) + 1);
}
System.out.println("the = " + counts.get("the"));
System.out.println("and = " + counts.get("and"));Shopping list
ArrayList<String> list = new ArrayList<>();
list.add("milk");
list.add("eggs");
System.out.println(list.size());📖 Key words
Tap a card to flip it over!
- ArrayList
- A list that can grow 📋
- HashMap
- Key–value storage 🗝️
- Generics <T>
- Says what type a collection holds 🏷️
- for-each
- Loops over every item 🔁
🏆 Challenge
Predict the output.
Challenge
ArrayList<Integer> nums = new ArrayList<>();
nums.add(5); nums.add(10); nums.add(15);
nums.remove(0);
System.out.println(nums);Knowledge Check Quiz
- How do you add to an ArrayList?
- What does map.get("k") return?
- What does ArrayList<String> mean?