{"id":"list-methods-for-each","slug":"for-each","title":"The for-each loop","text":"The last module went through lists with an index: `for (int i = 0; i < list.size(); i++)` and `list.get(i)`. When you just want every value, from the first to the last, Java has a shorter loop, the **for-each** loop:\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> planets = new ArrayList<>();\n        planets.add(\"Mercury\");\n        planets.add(\"Venus\");\n        planets.add(\"Earth\");\n\n        for (String planet : planets) {\n            System.out.println(planet + \" orbits the Sun\");\n        }\n    }\n}\n```\n\n```output\nMercury orbits the Sun\nVenus orbits the Sun\nEarth orbits the Sun\n```\n\nRead `for (String planet : planets)` as \"for each String `planet` in `planets`\".\n\n- The loop runs once for each value in the list. In each round, `planet` holds the next value: first `\"Mercury\"`, then `\"Venus\"`, then `\"Earth\"`.\n- The type before the name is the type of the list's values. For an `ArrayList<Integer>`, write `for (int number : numbers)`: each `Integer` comes out as a plain `int`.\n- You pick the name. The singular of the list's name, like `planet` for `planets`, reads well.\n\nThe same loop with an index needs a counter, a condition, `size()` and `get`:\n\n```java\nfor (int i = 0; i < planets.size(); i++) {\n    String planet = planets.get(i);\n    System.out.println(planet + \" orbits the Sun\");\n}\n```\n\n### When the index loop is still the right tool\n\nA for-each loop gives you the values, but not their places in the list. Use a loop with an index when:\n\n- you need the index itself, for example to print `1. Mercury`, or to compare a value with the one next to it;\n- you go through the list in another order, such as backwards from the last value;\n- you remove values from the list while going through it (step 4 shows why).\n\nFor everything else, such as printing, adding up or counting, the for-each loop is shorter, and there's no index to get wrong.\n\nA quick way to see a whole list at once: `System.out.println(planets)` prints `[Mercury, Venus, Earth]`, the values in square brackets. It's handy for checking your work.\n","task":"Fill in the blanks, so the for-each loop prints every task on the list. The program prints:\n\n```\n- water the plants\n- call the dentist\n- buy stamps\n```\n","kind":"fill","seed":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> tasks = new ArrayList<>();\n        tasks.add(\"water the plants\");\n        tasks.add(\"call the dentist\");\n        tasks.add(\"buy stamps\");\n\n        for ([[String task]] : [[tasks]]) {\n            System.out.println(\"- \" + task);\n        }\n    }\n}\n","solution":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> tasks = new ArrayList<>();\n        tasks.add(\"water the plants\");\n        tasks.add(\"call the dentist\");\n        tasks.add(\"buy stamps\");\n\n        for (String task : tasks) {\n            System.out.println(\"- \" + task);\n        }\n    }\n}\n","hints":["The first blank is the loop variable: its type and its name. The print line calls it `task`.","`for (String task : tasks)`: the list goes after the colon."],"tests":[{"name":"Output","stdin":"","expect":"- water the plants\n- call the dentist\n- buy stamps","hidden":false}],"require":[],"forbid":[],"more":[{"task":"Read the ingredients of a recipe until the line `end`, adding each one to the list `ingredients`. Then use a for-each loop to print `You need: ` and each ingredient, in order, and finally `Happy cooking!`. For the input `flour`, `butter`, `two eggs` and `end` the program prints:\n\n```\nYou need: flour\nYou need: butter\nYou need: two eggs\nHappy cooking!\n```\n","kind":"code","seed":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<String> ingredients = new ArrayList<>();\n\n    }\n}\n","solution":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<String> ingredients = new ArrayList<>();\n        while (true) {\n            String line = scanner.nextLine();\n            if (line.equals(\"end\")) {\n                break;\n            }\n            ingredients.add(line);\n        }\n\n        for (String ingredient : ingredients) {\n            System.out.println(\"You need: \" + ingredient);\n        }\n        System.out.println(\"Happy cooking!\");\n    }\n}\n","hints":["First a `while (true)` loop that reads a line, stops with `break` at `end`, and otherwise adds the line to `ingredients`.","After it: `for (String ingredient : ingredients) { ... }`, and `Happy cooking!` after that loop."],"tests":[{"name":"Test 1","stdin":"flour\nbutter\ntwo eggs\nend\n","expect":"You need: flour\nYou need: butter\nYou need: two eggs\nHappy cooking!","hidden":false},{"name":"Test 2","stdin":"end\n","expect":"Happy cooking!","hidden":true},{"name":"Test 3","stdin":"rice\nend\n","expect":"You need: rice\nHappy cooking!","hidden":true}],"require":[{"pattern":"for\\s*\\(\\s*\\w+\\s+\\w+\\s*:","message":"Print the ingredients with a for-each loop: `for (String ingredient : ingredients)`."}],"forbid":[]},{"task":"Things come out of a moving box in the opposite order to how they went in. Read items until the line `close`. Print `Packed: ` and each item in order with a for-each loop. Then print `Unpacked: ` and each item from the last to the first, with an index loop that counts down. For the input `books`, `lamp`, `mugs` the program prints:\n\n```\nPacked: books\nPacked: lamp\nPacked: mugs\nUnpacked: mugs\nUnpacked: lamp\nUnpacked: books\n```\n","kind":"code","seed":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<String> box = new ArrayList<>();\n\n    }\n}\n","solution":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<String> box = new ArrayList<>();\n        while (true) {\n            String item = scanner.nextLine();\n            if (item.equals(\"close\")) {\n                break;\n            }\n            box.add(item);\n        }\n\n        for (String item : box) {\n            System.out.println(\"Packed: \" + item);\n        }\n        for (int i = box.size() - 1; i >= 0; i--) {\n            System.out.println(\"Unpacked: \" + box.get(i));\n        }\n    }\n}\n","hints":["The for-each loop does the packing. A for-each loop can only go forwards, so unpacking needs an index.","The last index is `box.size() - 1`: `for (int i = box.size() - 1; i >= 0; i--)`, with `box.get(i)` inside."],"tests":[{"name":"Test 1","stdin":"books\nlamp\nmugs\nclose\n","expect":"Packed: books\nPacked: lamp\nPacked: mugs\nUnpacked: mugs\nUnpacked: lamp\nUnpacked: books","hidden":false},{"name":"Test 2","stdin":"radio\nclose\n","expect":"Packed: radio\nUnpacked: radio","hidden":true},{"name":"Test 3","stdin":"plant\nshoes\nclock\nkettle\nclose\n","expect":"Packed: plant\nPacked: shoes\nPacked: clock\nPacked: kettle\nUnpacked: kettle\nUnpacked: clock\nUnpacked: shoes\nUnpacked: plant","hidden":true}],"require":[{"pattern":"for\\s*\\(\\s*\\w+\\s+\\w+\\s*:","message":"Print the packed items with a for-each loop."},{"pattern":"\\.get\\s*\\(","message":"Unpack with an index loop that counts down and uses `get`."}],"forbid":[]}]}