Arrays and the collections framework
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- 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
Listis an ordered sequence that allows duplicates.ArrayListis the implementation you will use most.Setholds unique items.HashSetis fast and unordered.TreeSetkeeps items sorted.LinkedHashSetkeeps insertion order.Mapstores key-value pairs with unique keys.HashMapis the default.TreeMapsorts by key.Dequeworks as a queue or a stack.ArrayDequeis 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 need | Use |
|---|---|
| An ordered list you read by position | ArrayList |
| Unique items, fast contains | HashSet |
| Lookup by key | HashMap |
| Everything sorted | TreeSet or TreeMap |
| Insertion order preserved in a set or map | LinkedHashSet, LinkedHashMap |
| A stack or a queue | ArrayDeque |
Common mistakes
- Removing items inside a for-each loop. It throws
ConcurrentModificationException. Use an iterator, orremoveIf. - 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. Useequals. - Forgetting that
List.ofis immutable.
Try it yourself
- Read a sentence and print the number of distinct words using a
Set. - Store five student names with marks in a
Map, then print the name of the student with the top mark. - Use
removeIfto delete every even number from a list of 1 to 10.
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