Tutorials / Java: From Zero to Advanced / Arrays and the collections framework

Arrays and the collections framework

15 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

Holding many values

A program rarely handles one value at a time. You need a list of customers, a set of unique tags, a table that maps product codes to prices. Java gives you arrays for fixed-size data and the collections framework for everything else. The collections use generics, written with angle brackets, such as List<String>. The type inside the brackets says what the collection holds. We study generics themselves in a later lesson. For now, read List<String> as "a list of strings".

Arrays

An array has a fixed length, chosen when you create it. Elements are numbered from zero.

int[] scores = new int[5];            // five zeros
scores[0] = 80;
String[] days = {"Mon", "Tue", "Wed"};
System.out.println(days.length);      // length is a field, no brackets
System.out.println(days[3]);          // ArrayIndexOutOfBoundsException

The helper class java.util.Arrays offers sort, toString, fill, copyOf and equals. Printing an array directly shows something like [I@1b6d3586, so use Arrays.toString(array).

The main collections

  • List is an ordered sequence that allows duplicates. ArrayList is the implementation you will use most.
  • Set holds unique items. HashSet is fast and unordered. TreeSet keeps items sorted. LinkedHashSet keeps insertion order.
  • Map stores key-value pairs with unique keys. HashMap is the default. TreeMap sorts by key.
  • Deque works as a queue or a stack. ArrayDeque is the usual choice.

You declare variables with the interface type on the left, for example List<String> names = new ArrayList<>();. The empty <> is the diamond. The compiler fills in the type. Using the interface type means you can swap the implementation later by changing one word.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // Arrays
        int[] numbers = {5, 3, 9, 1};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));

        // List
        List<String> shopping = new ArrayList<>();
        shopping.add("milk");
        shopping.add("eggs");
        shopping.add("bread");
        shopping.add(1, "rice");              // insert at position 1
        shopping.remove("eggs");
        System.out.println(shopping + " size " + shopping.size());
        System.out.println(shopping.get(0) + ", first: " + shopping.getFirst()
                + ", last: " + shopping.getLast());   // getFirst and getLast arrived in Java 21
        Collections.sort(shopping);
        System.out.println(shopping);

        // Immutable list, handy for constants
        List<Integer> fixed = List.of(1, 2, 3);
        try {
            fixed.add(4);
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of returns an immutable list");
        }

        // Set removes duplicates
        Set<String> tags = new HashSet<>(List.of("java", "code", "java", "learn"));
        System.out.println(tags.size());       // 3
        System.out.println(tags.contains("code"));

        // Map: count word frequencies
        String text = "the cat and the dog and the bird";
        Map<String, Integer> counts = new TreeMap<>();
        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);
        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // Lookups with defaults
        Map<String, Double> prices = new HashMap<>();
        prices.put("tea", 250.0);
        prices.put("sugar", 180.0);
        System.out.println(prices.getOrDefault("coffee", 0.0));
        prices.putIfAbsent("tea", 999.0);       // keeps the existing value
        System.out.println(prices.get("tea"));

        // Queue and stack
        Deque<String> stack = new ArrayDeque<>();
        stack.push("a");
        stack.push("b");
        System.out.println(stack.pop());       // b

        // Sorting with a comparator
        List<String> words = new ArrayList<>(List.of("banana", "kiwi", "apple", "fig"));
        words.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        System.out.println(words);
    }
}

Walking through it

The array section sorts an int[] in place with Arrays.sort. The list section shows the usual operations. add appends, add(index, value) inserts, remove(value) removes the first match, get(index) reads. In Java 21, lists also have getFirst and getLast, which are tidy replacements for get(0) and get(size() - 1).

A word of caution about remove. On a List<Integer>, list.remove(1) removes the element at index 1, but list.remove(Integer.valueOf(1)) removes the value 1. The overloads are a well-known trap.

List.of, Set.of and Map.of create immutable collections. They throw UnsupportedOperationException if you try to change them, and they reject nulls. Immutable collections are a good default for data that should not change after it is built.

The HashSet built from a list with duplicates keeps only three entries. A set uses equals and hashCode to decide whether two items are the same. For strings and numbers, that works as you would expect.

The word counter uses merge. It means: put 1 if the key is absent, otherwise combine the old value and 1 using Integer::sum. This is shorter and safer than checking containsKey and then putting. The TreeMap prints the words sorted. The entrySet loop walks keys and values together. If you only need values, use values(). For only keys, use keySet().

The last example sorts by length first and alphabetically second using a comparator. We will see lambdas and method references like String::length in the streams lesson.

Choosing a collection

You needUse
An ordered list you read by positionArrayList
Unique items, fast containsHashSet
Lookup by keyHashMap
Everything sortedTreeSet or TreeMap
Insertion order preserved in a set or mapLinkedHashSet, LinkedHashMap
A stack or a queueArrayDeque

Common mistakes

  • Removing items inside a for-each loop. It throws ConcurrentModificationException. Use an iterator, or removeIf.
  • Using a mutable object as a map key and then changing it. The map can no longer find it.
  • Printing an array directly. Use Arrays.toString.
  • Using == to compare boxed numbers in a collection. Use equals.
  • Forgetting that List.of is immutable.

Try it yourself

  1. Read a sentence and print the number of distinct words using a Set.
  2. Store five student names with marks in a Map, then print the name of the student with the top mark.
  3. Use removeIf to delete every even number from a list of 1 to 10.
java
import java.util.*;

public class Main {

    public static void main(String[] args) {
        // Arrays
        int[] numbers = {5, 3, 9, 1};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));

        // List
        List<String> shopping = new ArrayList<>();
        shopping.add("milk");
        shopping.add("eggs");
        shopping.add("bread");
        shopping.add(1, "rice");              // insert at position 1
        shopping.remove("eggs");
        System.out.println(shopping + " size " + shopping.size());
        System.out.println(shopping.get(0) + ", first: " + shopping.getFirst()
                + ", last: " + shopping.getLast());   // getFirst and getLast arrived in Java 21
        Collections.sort(shopping);
        System.out.println(shopping);

        // Immutable list, handy for constants
        List<Integer> fixed = List.of(1, 2, 3);
        try {
            fixed.add(4);
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of returns an immutable list");
        }

        // Set removes duplicates
        Set<String> tags = new HashSet<>(List.of("java", "code", "java", "learn"));
        System.out.println(tags.size());       // 3
        System.out.println(tags.contains("code"));

        // Map: count word frequencies
        String text = "the cat and the dog and the bird";
        Map<String, Integer> counts = new TreeMap<>();
        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);
        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // Lookups with defaults
        Map<String, Double> prices = new HashMap<>();
        prices.put("tea", 250.0);
        prices.put("sugar", 180.0);
        System.out.println(prices.getOrDefault("coffee", 0.0));
        prices.putIfAbsent("tea", 999.0);       // keeps the existing value
        System.out.println(prices.get("tea"));

        // Queue and stack
        Deque<String> stack = new ArrayDeque<>();
        stack.push("a");
        stack.push("b");
        System.out.println(stack.pop());       // b

        // Sorting with a comparator
        List<String> words = new ArrayList<>(List.of("banana", "kiwi", "apple", "fig"));
        words.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        System.out.println(words);
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account