AI Hints
Home›Java Tutorial›HashMap, Looping Over a Map and HashSet
Java · Lesson 86 of 120

Looping Over a Map

Keys, values, entries.

⏱ 2 min read▶ Video at 1:49:21🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Sometimes you need to go through every pair in a map. You can loop over the keys, the values, or both together.

  • Every pair
  • Keys, values
  • Or both

Three ways to loop

A TreeMap is a map that keeps its keys sorted. Key set gives all the keys. Entry set gives each pair, as an entry. An entry has get key, and get value. And values gives just the values. Run it. The fruits come out in alphabetical order. Each one shows its stock. And the total is forty two.

Main.javajava
import java.util.Map;
import java.util.TreeMap;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>();
        stock.put("pears", 12);
        stock.put("apples", 30);
        stock.put("figs", 0);
        for (String fruit : stock.keySet()) System.out.print(fruit + " ");
        System.out.println();
        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            String status = e.getValue() > 0 ? "in stock" : "sold out";
            System.out.println(e.getKey() + ": " + e.getValue() + " (" + status + ")");
        }
        int total = 0;
        for (int n : stock.values()) total += n;
        System.out.println("Total fruit: " + total);
    }
}
Output
apples figs pears
apples: 30 (in stock)
figs: 0 (sold out)
pears: 12 (in stock)
Total fruit: 42

HashMap or TreeMap

Both are maps, with the same methods. The difference is order. Map is the general interface, which both of them implement.

KindOrderSpeed
HashMapno orderfastest
TreeMapkeys sortedfast
LinkedHashMapinsertion orderfast

Summary

Loop over key set, values, or entry set. Use a TreeMap when you want sorted keys. Next, a set, which holds no duplicates.

Key takeaways
  • keySet()
  • values()
  • entrySet()
Next up: HashSet — no duplicates