Lists and maps

Intermediate

Introduction

Arrays have a fixed size, chosen when they are created. Real programs rarely know in advance how many orders, students or words they will handle. Java's collections grow as needed and offer ready-made operations for adding, removing, searching and sorting. The two you will use most are lists, which keep items in order, and maps, which look values up by a key.

How it works

A list is declared with the List interface and created with ArrayList. The type in angle brackets says what it holds:

List<String> names = new ArrayList<>();
names.add("Rina");          // append
names.add(0, "Arif");       // insert at index 0
String first = names.get(0);
names.set(1, "Zoya");       // replace
names.remove("Zoya");       // remove by value
int n = names.size();
boolean has = names.contains("Arif");
Collections.sort(names);

List.of("a", "b") creates a fixed list you cannot change; wrap it in new ArrayList<>(...) when you need to.

Collections hold objects, not primitives, so a list of numbers is List<Integer>. Java converts between int and Integer automatically (autoboxing). Be careful with remove on a list of integers: list.remove(1) removes the item at index 1, while list.remove(Integer.valueOf(1)) removes the value 1.

A map stores key-value pairs:

Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 10);
int pens = stock.get("pen");                  // 10
int bags = stock.getOrDefault("bag", 0);      // 0, no key
stock.put("pen", stock.get("pen") - 1);       // update
stock.remove("pen");

get returns null for a missing key, so prefer getOrDefault or containsKey. A HashMap gives fast lookup but no particular order; a TreeMap keeps its keys sorted; a LinkedHashMap keeps them in insertion order.

Iterate a list with the enhanced for, and a map with entrySet(), which gives each key and value together: for (Map.Entry<String, Integer> e : map.entrySet()). Do not add or remove items from a collection while looping over it with for; that throws ConcurrentModificationException. Use an Iterator with its own remove, or removeIf.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // A list keeps order and allows repeats.
        List<String> words = new ArrayList<>();
        for (String w : "the cat and the hat and the bat".split(" ")) {
            words.add(w);
        }
        System.out.println(words.size() + " words, first " + words.get(0));

        // A map counts how often each word appears.
        Map<String, Integer> counts = new HashMap<>();
        for (String w : words) {
            counts.put(w, counts.getOrDefault(w, 0) + 1);
        }

        // A TreeMap keeps its keys sorted.
        Map<String, Integer> sorted = new TreeMap<>(counts);
        for (Map.Entry<String, Integer> e : sorted.entrySet()) {
            System.out.println(e.getKey() + ": " + e.getValue());
        }
        System.out.println("has dog? " + counts.containsKey("dog"));
    }
}
Open in compiler

Line by line

  1. The words go into an ArrayList, which keeps them in order, repeats included.
  2. getOrDefault returns 0 for a word seen for the first time, so each count starts at 1.
  3. Copying into a TreeMap sorts the words, and entrySet gives each word with its count.
  4. containsKey checks for a key without fetching a value.

Expected result

8 words, first the
and: 2
bat: 1
cat: 1
hat: 1
the: 3
has dog? false

In the real world

Lists hold the rows a program reads, the results of a search, the items in a cart. Maps hold indexes: users by id, prices by product code, counts by category. A large part of everyday Java code is building and walking through these two structures.

Common mistakes

  • Using get on a missing key and unboxing the null, which throws NullPointerException.
  • Removing items inside a for loop over the same list.
  • Confusing remove(index) with remove(value) on a list of Integer.
  • Expecting HashMap to keep insertion or sorted order.

Best practices

  • Declare variables with the interface (List, Map) and create them with a class (ArrayList, HashMap).
  • Use getOrDefault, merge or computeIfAbsent for counters and groups.
  • Choose TreeMap or LinkedHashMap when the order of keys matters.

Summary

ArrayList is a growable, ordered list with access by index; HashMap and TreeMap map keys to values, unordered or sorted. Collections hold objects, with autoboxing between primitives and wrapper types. Iterate lists directly and maps through entrySet, and never change a collection while looping over it with for.

Quick check

1. What does map.get(key) return when the key is missing?
2. Which map keeps its keys sorted?
3. On a List<Integer>, what does list.remove(1) remove?
4. Why is a list of numbers written List<Integer>, not List<int>?

Key takeaways

  • Use List and ArrayList for ordered, growable sequences; arrays have a fixed size.
  • Use Map, with HashMap for speed or TreeMap for sorted keys, to look values up by key.
  • Collections hold objects, so int is stored as Integer through autoboxing.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.