IntermediateLesson 10 of 205 min read

Collections: Lists, Sets and Maps

Learn ArrayList, HashSet, HashMap and TreeMap, when each one fits, how ordering and duplicates behave, and count words in a text with results verified against Python.

In this lesson you will

  • Use List, Set and Map
  • Understand ordering and duplicates
  • Count items with a map
  • Pick the right collection

About 28 minutes

Which bikes are rented most?

Hana wants to know how often each bike appears in the month’s bookings, which bikes appear at all, and a list of bookings in the order they came in. Arrays are too rigid for this, because the number of bookings is not known in advance. The collections framework gives you growing containers that each answer a different question.

Collection Remembers Duplicates Order Use it for
ArrayList A sequence Allowed Insertion order An ordered list that grows
HashSet A set of distinct values Not allowed Not guaranteed Checking membership, removing duplicates
TreeSet / TreeMap Sorted values or keys Not allowed Sorted Reports in alphabetical order
HashMap Key to value pairs Unique keys Not guaranteed Looking things up by key, counting

All of them are generic, which means you say what they hold in angle brackets: List holds strings. Because collections can only hold objects, ints are boxed into Integer automatically. A HashMap finds a key by computing its hashCode, which is why lesson 7 insisted on a matching equals and hashCode, and its lookups take about the same time however large the map is. Do not rely on the iteration order of a HashMap or HashSet, since it is an implementation detail. If you need sorted output, use a TreeMap, and if you need insertion order, use a LinkedHashMap.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String text = "city1 trail2 city1 tandem3 city1 trail2 city4 city1 trail2 tandem3";
        List<String> bookings = new ArrayList<>(Arrays.asList(text.split(" ")));
        System.out.println("bookings: " + bookings.size() + ", first: " + bookings.get(0));
        Set<String> distinct = new HashSet<>(bookings);
        System.out.println("distinct bikes: " + distinct.size());
        Map<String, Integer> counts = new HashMap<>();
        for (String b : bookings) counts.merge(b, 1, Integer::sum);
        Map<String, Integer> sorted = new TreeMap<>(counts);
        System.out.println("sorted by name: " + sorted);
        String top = null; int best = 0;
        for (Map.Entry<String, Integer> e : counts.entrySet()) if (e.getValue() > best) { best = e.getValue(); top = e.getKey(); }
        System.out.println("most rented: " + top + " (" + best + " times)");
        System.out.println("tandem3 booked? " + counts.containsKey("tandem3") + ", scooter9 booked? " + counts.containsKey("scooter9") + ", default 0: " + counts.getOrDefault("scooter9", 0));
        bookings.removeIf(b -> b.equals("city1"));
        System.out.println("after removing city1: " + bookings.size() + " bookings left");
        List<Integer> nums = new ArrayList<>(List.of(5, 3, 8, 1));
        Collections.sort(nums);
        System.out.println("sorted list: " + nums + ", max " + Collections.max(nums));
    }
}
bookings: 10, first: city1
distinct bikes: 4
sorted by name: {city1=4, city4=1, tandem3=2, trail2=3}
most rented: city1 (4 times)
tandem3 booked? true, scooter9 booked? false, default 0: 0
after removing city1: 6 bookings left
sorted list: [1, 3, 5, 8], max 8

The text held 10 bookings, and a HashSet reduced them to 4 distinct bikes, which is the quickest way to remove duplicates. The map counted each bike with merge, which adds one to an existing count or starts a count at one, and the TreeMap printed the counts in alphabetical order: {city1=4, city4=1, tandem3=2, trail2=3}. The most rented bike was city1, with 4 bookings. The getOrDefault call is a tidy way to ask for a key that might be missing without checking for null. After removeIf deleted every city1 booking, 6 bookings were left, and the sorted list shows Collections.sort and Collections.max at work.

The HashMap itself printed nothing in this program, and that was on purpose: its order is not defined, so the course sorted it into a TreeMap before showing it, to make the output the same on every machine. Whenever output order matters, say so in the code with a sorted or linked collection, and never discover the order by experiment.

Check by hand: counting the words, city1 appears 4 times, trail2 3 times, tandem3 2 times and city4 once, which adds to 10. Python’s collections.Counter gave the same counts, {‘city1’: 4, ‘city4’: 1, ‘tandem3’: 2, ‘trail2’: 3}, and the two lists of ten bookings had the same most common item.

Choosing in practice

A useful way to choose is to ask what question you will ask the collection most often. If it is “what is item number i”, you want a list. If it is “have I seen this before”, you want a set. If it is “what goes with this key”, you want a map. Asking the question first keeps you from reaching for ArrayList every time, which works but makes membership tests slow on large data, since a list must look at every element while a hash set jumps straight to the answer.

Do not change a list while looping over it

Removing items inside a for-each loop throws a ConcurrentModificationException. Use removeIf or an iterator instead.

Declare by interface

Write List bookings = new ArrayList(); and not ArrayList bookings. You can then switch the implementation without touching the rest of the code.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.

Practice

Count the words of a paragraph you write, ignoring case, and print the three most common. Use a Set to find the words that appear in one paragraph but not another. Think about which collection you would choose for a queue of bookings that must be handled in order.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which collection removes duplicates?

  1. ArrayList
  2. Array
  3. HashSet
  4. StringBuilder

A set holds distinct values.

Which structure stores key to value pairs?

  1. Set
  2. Map
  3. List
  4. Queue

HashMap and TreeMap.

Which map keeps keys sorted?

  1. HashMap
  2. TreeMap
  3. Array
  4. Vector only

Sorted by natural order.

Why must keys have equals and hashCode?

  1. Hash lookups depend on them
  2. Maps need a file
  3. They make keys faster to type
  4. It is only a convention

Lesson 7 covered the pair.

What does merge(b, 1, Integer::sum) do?

  1. Adds 1 to the count or starts at 1
  2. Removes the key
  3. Sorts the map
  4. Copies the map

A neat counting idiom.

Summary

  • List keeps order and allows duplicates; Set holds distinct values; Map stores key to value pairs.
  • HashMap and HashSet have no guaranteed order; TreeMap sorts.
  • Keys need consistent equals and hashCode.
  • Declare variables by interface.

Next lesson

Lesson 11 covers generics, records and enums.

Questions

When should I use an array instead of an ArrayList?

When the size is fixed and you want primitives without boxing. Use ArrayList otherwise.

What are generics?

A way to say what type a collection holds so the compiler checks it, such as List<String>.

Is HashMap thread-safe?

No. For concurrent use, ConcurrentHashMap and other tools exist, which the concurrency lesson mentions.

Progress is saved in this browser.