Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JV
Java
0/14 completed
Beginner
Hello JavaVariables and typesControl flowMethodsArrays and strings
Intermediate
Classes and objectsInheritance and interfacesCollectionsExceptions
Advanced
GenericsLambdas and streamsRecords, enums and pattern matching
Pro
Concurrency and virtual threadsBuild tools, testing and real projects
Tracks / Java / Intermediate

Collections

Arrays have a fixed size. Real programs need lists that grow, lookups by key, and sets of unique values. The Java Collections Framework in java.util provides them, and you'll use them in nearly every program.

Interface Common implementation Use when you need…
List ArrayList An ordered, growable list (duplicates allowed)
Set HashSet, LinkedHashSet, TreeSet Unique values
Map HashMap, LinkedHashMap, TreeMap Key → value lookups
Deque / Queue ArrayDeque, PriorityQueue Stacks, queues, "next most urgent"

ArrayList

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();      // <String>: holds Strings only
        fruits.add("banana");
        fruits.add("apple");
        fruits.add("cherry");
        fruits.add(0, "mango");                       // insert at a position

        System.out.println(fruits);
        System.out.println(fruits.get(1) + ", size " + fruits.size());
        System.out.println(fruits.contains("apple") + " at " + fruits.indexOf("apple"));

        fruits.remove("banana");
        fruits.set(0, "kiwi");
        Collections.sort(fruits);
        System.out.println(fruits);

        for (String f : fruits) System.out.print(f.toUpperCase() + " ");
        System.out.println();
    }
}
Output
[mango, banana, apple, cherry]
banana, size 4
true at 2
[apple, cherry, kiwi]
APPLE CHERRY KIWI 

Declare variables with the interface type (List<String>) and choose the implementation once, on the right (new ArrayList<>()). The <> ("diamond") repeats the type for you.

Collections hold objects: wrapper types

Collections can't hold primitives like int; they use wrapper classes (Integer, Double, Boolean…). Java converts automatically ("autoboxing"):

java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(List.of(70, 92, 55, 88));
        int total = 0;
        for (int s : scores) total += s;           // unboxing Integer → int
        System.out.println(total / scores.size());

        scores.removeIf(s -> s < 60);              // a lambda: more in a later lesson
        System.out.println(scores);

        List<String> fixed = List.of("a", "b");     // an immutable list
        try {
            fixed.add("c");
        } catch (UnsupportedOperationException e) {
            System.out.println("Can't add to an immutable list");
        }
    }
}
Output
76
[70, 92, 88]
Can't add to an immutable list

List.of(...), Set.of(...) and Map.of(...) create immutable collections: perfect for constants, but you can't add to them. Wrap one in new ArrayList<>(...) when you need to change it.

HashMap

A map stores key → value pairs. Looking up a key is fast however many entries there are:

java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Double> prices = new HashMap<>();
        prices.put("laptop", 899.0);
        prices.put("mug", 8.99);
        prices.put("lamp", 29.0);
        prices.put("mug", 9.49);                     // same key: replaces the value

        System.out.println(prices.get("mug"));
        System.out.println(prices.get("phone"));     // missing key: null
        System.out.println(prices.getOrDefault("phone", 0.0));
        System.out.println(prices.containsKey("lamp") + " " + prices.size());

        for (Map.Entry<String, Double> e : prices.entrySet()) {
            System.out.println(e.getKey() + " → " + e.getValue());
        }
    }
}
Output
9.49
null
0.0
true 3
lamp → 29.0
laptop → 899.0
mug → 9.49

⚠️ A HashMap doesn't promise any order: notice the entries didn't come out in the order they were added, and the order could differ in another Java version. Use LinkedHashMap to keep insertion order, or TreeMap to keep keys sorted.

Counting and grouping

Two patterns you'll write over and over:

java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String text = "the cat and the hat and the bat";

        Map<String, Integer> counts = new TreeMap<>();          // sorted by key
        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);                // add 1, or start at 1
        }
        System.out.println(counts);

        Map<Character, List<String>> byLetter = new TreeMap<>();
        for (String w : List.of("apple", "avocado", "banana", "blueberry", "cherry")) {
            byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
        }
        System.out.println(byLetter);
    }
}
Output
{and=2, bat=1, cat=1, hat=1, the=3}
{a=[apple, avocado], b=[banana, blueberry], c=[cherry]}

Sets

java
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<String> tags = new LinkedHashSet<>();       // keeps insertion order
        tags.add("java");
        tags.add("sql");
        System.out.println(tags.add("java"));           // already there: returns false
        System.out.println(tags);

        Set<String> asha = new TreeSet<>(Set.of("java", "sql", "docker"));
        Set<String> rahul = Set.of("java", "python", "docker");

        Set<String> both = new TreeSet<>(asha);
        both.retainAll(rahul);                          // intersection
        Set<String> onlyAsha = new TreeSet<>(asha);
        onlyAsha.removeAll(rahul);                      // difference
        System.out.println(both + " " + onlyAsha);
        System.out.println(new HashSet<>(java.util.List.of(1, 2, 2, 3, 3, 3)).size());
    }
}
Output
false
[java, sql]
[docker, java] [sql]
3

Queues and stacks

java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.PriorityQueue;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();     // first in, first out
        queue.offer("first");
        queue.offer("second");
        System.out.println(queue.poll() + ", then " + queue.peek());

        Deque<Integer> stack = new ArrayDeque<>();    // last in, first out
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop() + " " + stack.pop());

        PriorityQueue<Integer> tasks = new PriorityQueue<>();   // smallest first
        tasks.addAll(java.util.List.of(5, 1, 4, 2));
        while (!tasks.isEmpty()) System.out.print(tasks.poll() + " ");
        System.out.println();
    }
}
Output
first, then second
3 2
1 2 4 5 

Choosing the right collection

  • Need order and index access? ArrayList.
  • Need "is this already there?" fast, with no duplicates? HashSet.
  • Need to look things up by a key? HashMap.
  • Need sorted keys or values? TreeMap / TreeSet.
  • Need a queue or stack? ArrayDeque. Need the "smallest/most urgent" item next? PriorityQueue.

Don't modify a collection while looping over it

java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        nums.removeIf(n -> n % 2 == 0);       // the safe way
        System.out.println(nums);

        for (Integer n : nums) {
            if (n == 1) nums.remove(n);       // changing the list mid-loop
        }
    }
}
Output
[1, 3, 5]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1096)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1050)
	at Main.main(Main.java:10)

Practice

  1. Read the words of a sentence into an ArrayList, remove duplicates while keeping order (hint: LinkedHashSet), and print them.
  2. Build a phone book with a TreeMap<String, String>, and print it in alphabetical order.
  3. Count the frequency of each character in "mississippi" with merge.
✎ Check your understanding

1.Which collection keeps only unique values?

2.Why write List<String> names = new ArrayList<>(); instead of ArrayList<String> names = ...?

3.What does map.get("missing") return for a HashMap?

← Inheritance and interfaces