← All lessons
Intermediate Java · Lesson 5 of 9

Lists, maps and sets

Arrays have a fixed size. Most real data doesn't: a shopping cart grows and shrinks. Java's collections are classes that hold any number of objects. The three you'll use most are lists, maps and sets. They live in java.util (the examples import it for you).

ArrayList

A list keeps items in order and lets you add, remove and look up by index. ArrayList is the everyday one. The type in angle brackets, <String>, says what it holds; on the right <> lets Java fill it in.

Java
List<String> cart = new ArrayList<>();
cart.add("milk");
cart.add("eggs");
cart.add("bread");
System.out.println(cart);
System.out.println(cart.size() + " items, first is " + cart.get(0));
cart.remove("eggs");
cart.add(0, "apples");
cart.set(2, "rolls");
System.out.println(cart);
System.out.println(cart.contains("milk") + " " + cart.indexOf("rolls"));
Prints
[milk, eggs, bread]
3 items, first is milk
[apples, milk, rolls]
true 2

Lists print nicely without help. size() is the count (where arrays say length), get(i) reads, set(i, x) replaces, add(i, x) inserts and remove takes out by value or by index. List.of("a", "b") makes a small list you can't change, handy for fixed data.

Wrapper types

Collections can only hold objects, not the simple types int, double, boolean and char. Each has an object version, its wrapper: Integer, Double, Boolean, Character. So a list of numbers is List<Integer>, and Java converts back and forth for you (autoboxing).

Java
List<Integer> scores = new ArrayList<>(List.of(70, 95, 82));
scores.add(60);
int total = 0;
for (int s : scores) total += s;
System.out.println(total);
Collections.sort(scores);
System.out.println(scores);
System.out.println(Collections.max(scores));
Prints
307
[60, 70, 82, 95]
95

One trap: a List<Integer>'s remove(1) removes the item at index 1, not the number 1. Write remove(Integer.valueOf(1)) for the number. And compare two Integers with .equals, like strings.

HashMap

A map stores pairs: a key and the value that goes with it, like a word and its meaning, or a name and a phone number. You look values up by key, fast, however big the map is. Keys are unique; putting a key that's already there replaces its value.

Java
Map<String, Integer> stock = new HashMap<>();
stock.put("apples", 12);
stock.put("pears", 4);
stock.put("apples", 10);
System.out.println(stock.get("apples"));
System.out.println(stock.get("kiwis"));
System.out.println(stock.getOrDefault("kiwis", 0));
System.out.println(stock.containsKey("pears") + " " + stock.size());
Prints
10
null
0
true 2

get gives null for a key that isn't there; getOrDefault gives a fallback instead. A classic use is counting: for each word, add one to its count, starting from 0.

Java
String[] words = "the cat and the hat and the bat".split(" ");
Map<String, Integer> counts = new TreeMap<>();
for (String w : words) {
    counts.put(w, counts.getOrDefault(w, 0) + 1);
}
System.out.println(counts);
for (Map.Entry<String, Integer> e : counts.entrySet()) {
    if (e.getValue() > 1) System.out.println(e.getKey() + " x" + e.getValue());
}
Prints
{and=2, bat=1, cat=1, hat=1, the=3}
and x2
the x3

A HashMap keeps its entries in no particular order, so this example uses TreeMap, which keeps the keys sorted (LinkedHashMap keeps the order you added them). All three are Maps with the same methods. entrySet() gives each key and value pair to loop over.

HashSet

A set holds each value at most once and answers "is this in here?" fast. Adding something already there does nothing, so sets are the easy way to remove duplicates.

Java
Set<String> seen = new HashSet<>();
System.out.println(seen.add("red"));
System.out.println(seen.add("blue"));
System.out.println(seen.add("red"));
System.out.println(seen.size() + " " + seen.contains("blue"));
List<Integer> nums = List.of(3, 1, 3, 2, 1);
System.out.println(new TreeSet<>(nums));
Prints
true
true
false
2 true
[1, 2, 3]

Which one? Items in order, maybe repeated: a List. Look up by a key: a Map. Each thing once, or "have I seen this?": a Set.

Practice

What does this print?

List<String> xs = new ArrayList<>();
xs.add("a");
xs.add("b");
xs.add("c");
xs.remove(0);
System.out.println(xs);
More info

Quick reference

List<T> xs = new ArrayList<>();An ordered list that grows.
add / get / set / remove / sizeThe list basics.
Integer, Double, Boolean, CharacterObject versions of int, double, boolean, char.
Map<K, V> m = new HashMap<>();Key and value pairs.
put / get / getOrDefault / containsKeyThe map basics; get gives null if missing.
TreeMap / LinkedHashMapMaps sorted by key / in the order added.
Set<T> s = new HashSet<>();Each value once; contains is fast.
Collections.sort(xs)Sort a list in place.

Related courses