×

java · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Loop over a map's keys, or over each key and value together.

visits every key, and ages.get(name) fetches its value. To get both at once, loop over ages.entrySet(). Each is a Map.Entry, with getKey() and getValue() to read its two halves.

A HashMap keeps its keys in a jumbled order that suits Java, not you. Want them sorted? Use a instead. It works the same way, but always keeps its keys in order, so loops visit them A to Z.

new TreeMap<>(ages) makes a sorted copy of any map.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> ages = new TreeMap<>();
        ages.put("Zoe", 7);
        ages.put("Ava", 9);
        ages.put("Leo", 11);
        for (String name : ages.keySet()) {
            System.out.println(name + " is " + ages.get(name));
        }
        for (Map.Entry<String, Integer> entry : ages.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Printing a whole map shows it in curly brackets, like {Ava=9, Leo=11}.