Aral Code

Object-Oriented Programming Lesson 19 of 21

Java ArrayList and HashMap

Use ArrayList for lists that grow and shrink — add, get, set, remove, contains, sort — and HashMap for key–value lookups such as a price list or vote counter.

Arrays have a fixed size. Real programs often don't know in advance how many items they'll have: students enrolling, orders coming in. Java's collections solve this. The two you'll use most are ArrayList and HashMap.

ArrayList basics

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ana");
        names.add("Ben");
        names.add("Carla");
        names.add(1, "Dan");        // insert at index 1

        System.out.println(names);
        System.out.println("Size: " + names.size());
        System.out.println("First: " + names.get(0));

        names.set(2, "Benjie");     // replace
        names.remove("Carla");      // remove by value
        names.remove(0);            // remove by index
        System.out.println(names);
        System.out.println("Has Dan? " + names.contains("Dan"));
    }
}

Output

[Ana, Dan, Ben, Carla]
Size: 4
First: Ana
[Dan, Benjie]
Has Dan? true
MethodDoes
add(x) / add(i, x)Add at the end / at index i
get(i)Read item i
set(i, x)Replace item i
remove(i) / remove(x)Remove by index / by value
size()Number of items
contains(x), indexOf(x)Search
clear(), isEmpty()Empty the list / check if empty

Unlike arrays (length), ArrayList uses size(). And unlike arrays, printing an ArrayList shows its contents nicely.

Generics: the type in angle brackets

ArrayList<String> means "a list of Strings". Collections can't hold primitives directly, so use the wrapper class: Integer for int, Double for double:

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

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> grades = new ArrayList<>();
        grades.add(88);
        grades.add(72);
        grades.add(95);
        grades.add(81);

        int sum = 0;
        for (int g : grades) sum += g;
        System.out.println("Average: " + (double) sum / grades.size());

        Collections.sort(grades);
        System.out.println("Sorted: " + grades);
        System.out.println("Max: " + Collections.max(grades));

        grades.removeIf(g -> g < 75);
        System.out.println("Passing: " + grades);
    }
}

Output

Average: 84.0
Sorted: [72, 81, 88, 95]
Max: 95
Passing: [81, 88, 95]

g -> g < 75 is a lambda: a tiny function that says which items to remove.

A list of objects

import java.util.ArrayList;
import java.util.Comparator;

class Student {
    String name;
    double average;
    Student(String name, double average) { this.name = name; this.average = average; }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("Ana", 91.5));
        list.add(new Student("Ben", 84.0));
        list.add(new Student("Carla", 95.2));

        list.sort(Comparator.comparingDouble((Student s) -> s.average).reversed());
        int rank = 1;
        for (Student s : list) {
            System.out.printf("%d. %-6s %.1f%n", rank++, s.name, s.average);
        }
    }
}

Output

1. Carla  95.2
2. Ana    91.5
3. Ben    84.0

HashMap: key–value pairs

A HashMap stores values you look up by a key, like a dictionary:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Double> prices = new HashMap<>();
        prices.put("pandesal", 25.0);
        prices.put("kape", 8.0);
        prices.put("itlog", 9.0);

        System.out.println("Kape: ₱" + prices.get("kape"));
        prices.put("kape", 10.0);                       // update
        System.out.println("Kape now: ₱" + prices.get("kape"));
        System.out.println("Has asukal? " + prices.containsKey("asukal"));
        System.out.println("Asukal: " + prices.getOrDefault("asukal", 0.0));
        System.out.println("Items: " + prices.size());
    }
}

Output

Kape: ₱8.0
Kape now: ₱10.0
Has asukal? false
Asukal: 0.0
Items: 3

Counting with a HashMap

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String[] votes = {"Ana", "Ben", "Ana", "Carla", "Ana", "Ben"};
        TreeMap<String, Integer> tally = new TreeMap<>();   // sorted by key
        for (String v : votes) {
            tally.put(v, tally.getOrDefault(v, 0) + 1);
        }
        for (var entry : tally.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output

Ana: 3
Ben: 2
Carla: 1

HashMap doesn't keep any order; TreeMap keeps keys sorted, and LinkedHashMap keeps the order you inserted them.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. How do you get the number of items in an ArrayList?
2. Which declaration is correct?
3. Which HashMap method returns a default when the key is missing?
4. Which map keeps keys in sorted order?

By Sir Reyel · Last updated 2026-12-04