Codiqo

Learn Java · lesson 32 of 61 · about 9 minutes

Iterating Collections

Count the tickets sold at the door by type: loop over lists and over map entries, and count things with a map.

What you'll learn

  • Loop over a list with for-each
  • Loop over a map's entrySet
  • Count occurrences with merge

Sales at the door

At the door, tickets are sold one at a time, and each sale is typed in as its type: Adult, Child or Senior. The desk counts them in a map from type to number sold, adding 1 with getOrDefault(type, 0) + 1. Then it loops over the map's entries to print each count, add up the takings with the ticketPrice method from earlier, and find the type that sold most. A TreeMap keeps the types in alphabetical order, so the output is the same every time.

Looping

  • for (String name : list) visits each item of a list
  • for (Map.Entry<String, Integer> e : map.entrySet()) visits each pair; use e.getKey() and e.getValue()
  • counts.merge(word, 1, Integer::sum) adds 1 to a count, starting at 1 for a new word

Counting votes

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        List<String> votes = List.of("py", "js", "py", "java", "py", "js");
        TreeMap<String, Integer> counts = new TreeMap<>();
        for (String v : votes) counts.merge(v, 1, Integer::sum);

        String winner = "";
        int best = 0;
        for (Map.Entry<String, Integer> e : counts.entrySet()) {
            System.out.println(e.getKey() + " " + e.getValue());
            if (e.getValue() > best) {
                best = e.getValue();
                winner = e.getKey();
            }
        }
        System.out.println("Winner: " + winner);
    }
}

Output

java 1
js 2
py 3
Winner: py

Tip

List.of(...) makes a quick list that can't be changed. Use new ArrayList<>(List.of(...)) when you need to add to it.

Tip

Don't add to or remove from a list while a for-each loop is going through it: Java throws a ConcurrentModificationException. Use remove(value) outside the loop, or removeIf.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.