To loop through every key in a HashMap, use .keySet(). It returns a Set containing all the keys:
for (String name : ages.keySet()) {
System.out.println(name);
}
Inside the loop, you can call .get() on each key to retrieve its value. This is the simplest way to iterate, but it costs lookups per entry: one in .keySet() and one in .get().
The order of keys is not guaranteed. You might insert "Alice", "Bob", "Carol" and see them come out as "Bob", "Carol", "Alice". If you need a predictable order, you will need a different map type. I'll show you those options later in this section.