Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList forEach() method
Syntax and Examples


Introduction

The forEach() method in Java's ArrayList provides a concise way to perform an action on each element of the list. It’s a functional approach that avoids traditional loops (like for or enhanced for) for simpler iteration tasks. Think of it as saying, "For each item in this list, do something with it." This is particularly useful when you want to process data within an arraylist without needing the index.

Syntax


public void forEach(Consumer<? super E> action)

Parameters

Parameter Description
action A Consumer functional interface that represents the action to be performed on each element. This is essentially a function that accepts an element of type E and does something with it (doesn't return anything).

Return Value

The forEach() method returns void. It doesn't produce any value; its purpose is solely to execute the provided action on each element.

Examples

Example 1: Printing Each Element

This example demonstrates how to print each element of an ArrayList using a lambda expression as the Consumer. We'll create a list of strings and use forEach to simply display them.


import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; // Import Consumer interface

public class ForEachExample1 {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(
                List.of("Alice", "Bob", "Charlie")
        );

        names.forEach(name -> System.out.println(name)); // Lambda expression for printing
    }
}


Alice
Bob
Charlie

Explanation: The lambda expression name -> System.out.println(name) is the Consumer. For each string in the names list, this lambda takes the string (represented by the parameter name) and prints it to the console.

Example 2: Modifying Elements

This example shows how to modify elements within an ArrayList using a forEach loop. We will create a list of integers, and increase each value by 1 during iteration.


import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ForEachExample2 {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(
                List.of(1, 2, 3, 4, 5)
        );

        numbers.forEach(number -> number += 1); // Incorrect: Modifying in place is not allowed directly

       System.out.println(numbers); // Prints the original list because forEach doesn't modify the underlying data
    }
}

[1, 2, 3, 4, 5]

Explanation: The forEach method in Java ArrayList does not directly modify the elements of the list. The lambda expression attempts to increment number by one, but this operation doesn't affect the original values inside the list itself. If you need to change the contents of a list during iteration, it is best to use other techniques like creating a new list or using an iterator.

Example 3: Using with Objects

This example demonstrates how to use forEach with a list of custom objects. We'll create a simple class and then iterate through a list of these objects, printing a property of each one.


import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class ForEachExample3 {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>(
                List.of(new Person("Alice"), new Person("Bob"), new Person("Charlie"))
        );

        people.forEach(person -> System.out.println(person.getName()));
    }
}


Alice
Bob
Charlie

Explanation: Here, the Consumer lambda expression accesses the getName() method of each Person object in the list and prints the name to the console. This shows how you can perform operations on objects contained within an ArrayList.

Example 4: Using with a Method Reference

This example showcases using a method reference instead of a lambda expression. It's a shorthand notation when your lambda expression simply calls an existing method.


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

public class ForEachExample4 {
    public static void printUpperCase(String s) {
        System.out.println(s.toUpperCase());
    }

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(
                List.of("hello", "world")
        );

        words.forEach(ForEachExample4::printUpperCase); // Method reference
    }
}

HELLO
WORLD

Explanation: The ForEachExample4::printUpperCase is a method reference. It's equivalent to the lambda expression s -> ForEachExample4.printUpperCase(s). This makes the code more concise when you are simply calling an existing method on each element.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M