TL ; DR:
Loop over a map's entrySet() to visit every key with its value. Each entry has getKey() and getValue().
HashMap<String, Integer> stock = new HashMap<>();
stock.put("apples", 5);
stock.put("pears", 2);
for (Map.Entry<String, Integer> entry : stock.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
// pears 2
// apples 5 (in any order)
Full lesson:
A loop can visit every entry of a map, one at a time. The loop body runs once per key.
entrySet() hands the loop each entry of the map. An entry is a key with its value. Its type is Map.Entry<String, Integer>.
Loop over keySet() to get only the keys. You can still read each value with get.
for (String fruit : stock.keySet()) {
System.out.println(fruit + " " + stock.get(fruit));
}
The order: a HashMap has no fixed order. The entries may come in any order. A total or a count comes out the same in any order. Those are safe answers.
Watch out: don't add or remove keys inside the loop. Java stops with a ConcurrentModificationException.
Your task
A game keeps each player's points in scores. The variables total and count start at 0.
Loop over scores. Add each entry's value to total. Count the players with 10 points or more in count.
The code at the bottom prints both.
Expected output:
43
2Free plan: 30 tutor messages. PRO is unlimited.
