Java Collections: ArrayList and HashMap

The Java Collections Framework provides ready-made data structures for storing groups of objects. Unlike arrays, collections such as ArrayList and HashMap grow and shrink automatically and come with many helpful methods.

ArrayList

An ArrayList is a resizable, ordered list. The type in angle brackets says what it stores. Declare variables with the List interface so you can swap implementations later.

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

public class Main {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>();
        tasks.add("Write code");
        tasks.add("Test code");
        tasks.add(0, "Plan");
        System.out.println(tasks);
        System.out.println(tasks.get(1) + ", size " + tasks.size());
        tasks.set(2, "Test everything");
        tasks.remove("Plan");
        System.out.println(tasks);
        System.out.println(tasks.contains("Write code"));
        for (String t : tasks) System.out.println("- " + t);
    }
}
[Plan, Write code, Test code]
Write code, size 3
[Write code, Test everything]
true
- Write code
- Test everything

Sorting a List

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

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(5, 2, 9, 1));
        nums.sort(null); // natural order
        System.out.println(nums);
        nums.sort(Comparator.reverseOrder());
        System.out.println(nums);

        List<String> words = new ArrayList<>(List.of("kiwi", "banana", "fig"));
        words.sort(Comparator.comparing(String::length));
        System.out.println(words);
        nums.removeIf(n -> n < 3);
        System.out.println(nums);
    }
}
[1, 2, 5, 9]
[9, 5, 2, 1]
[fig, kiwi, banana]
[9, 5]

List.of creates an immutable list, so we wrap it in new ArrayList to get one we can sort. Collections store objects, so int values are automatically boxed into Integer.

HashMap

A HashMap stores key-value pairs. Keys are unique; putting an existing key replaces its value. Lookup by key is very fast.

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

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("apples", 40);
        stock.put("pears", 12);
        stock.put("apples", 35); // replaces 40

        System.out.println(stock.get("apples"));
        System.out.println(stock.getOrDefault("plums", 0));
        System.out.println(stock.containsKey("pears"));

        String text = "the cat and the hat";
        Map<String, Integer> counts = new HashMap<>();
        for (String w : text.split(" ")) {
            counts.merge(w, 1, Integer::sum);
        }
        System.out.println(counts.get("the"));

        for (var entry : Map.of("a", 1).entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}
35
0
true
2
a -> 1

HashMap does not keep insertion order. Use LinkedHashMap to keep the order you inserted, or TreeMap to keep keys sorted.

HashSet

A Set stores unique values only, which makes it perfect for removing duplicates or fast membership tests.

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        List<String> visits = List.of("home", "about", "home", "blog", "about");
        Set<String> unique = new TreeSet<>(visits); // sorted and unique
        System.out.println(unique);
        System.out.println(unique.add("home"));
    }
}
[about, blog, home]
false

Choosing a Collection

  • ArrayList: ordered list with fast index access; the everyday default.
  • LinkedList / ArrayDeque: queues and stacks (ArrayDeque is usually faster).
  • HashMap: look up values by key.
  • HashSet: unique items, fast contains checks.
  • TreeMap / TreeSet: keep items sorted.

Frequently asked questions

What is the difference between an array and an ArrayList in Java?

An array has a fixed size and can hold primitives. An ArrayList grows automatically, holds only objects, and offers methods like add, remove and contains.

Does HashMap keep insertion order?

No. Use LinkedHashMap if you need insertion order, or TreeMap for keys sorted in natural order.

Why can I not write ArrayList<int>?

Generics only work with reference types. Use the wrapper class instead, ArrayList<Integer>, and Java will box and unbox values automatically.