How do I use for-each in Java?

Using for-each command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.

package org.kodejava.example.lang;

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

        for (Integer i : numbers) {
            System.out.println("Number: " + i);
        }

        List<String> names = new ArrayList<String>();
        names.add("James");
        names.add("Joshua");
        names.add("Scott");

        for (String name : names) {
            System.out.println("Name: " + name);
        }
    }
}

How do I use ArrayList class?

In this example we will learn how to use the java.util.ArrayList class. An ArrayList is part of the Java Collection Framework. By using this class we can create a dynamic size array of data, which means we can add or remove elements from the array dynamically.

In the code below we will see the demonstration on how to create an instance of ArrayList, add some elements, remove elements and iterate through the entire ArrayList elements either using a for-loop or using the for-each syntax.

We can also see how to convert the ArrayList into an array object using the toArray() method. And we use the Arrays.toString() utility method when we want to print the content of an array.

When creating a class instance it is a good practice to use the interface as the type of variable instead of the concrete type directly. This can make us easily update our code if we don’t want to use ArrayList anymore sometime in the future.

And here is the code snippet:

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Add items into ArrayList
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Remove the third item from ArrayList, first index = 0
        list.remove(2);

        // Iterate ArrayList item using for loop statement
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using for-each statement
        for (String item : list) {
            System.out.println("Item = " + item);
        }

        // Convert ArrayList into array of object
        String[] array = list.toArray(new String[list.size()]);
        System.out.println("Items = " + Arrays.toString(array));
    }
}

Executing the program will give us the following output printed in our console.

Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Items = [Item 1, Item 2]