Java forEach loop

Java forEach loop is a feature introduced in Java 8 that allows you to iterate over elements in a collection and perform a certain operation on each element using a lambda expression. It provides a more concise and expressive way of writing loops as compared to the traditional for loop or the enhanced for loop (for-each loop).

Here’s an example of how to use the forEach loop to iterate over an ArrayList of integers and print each element:

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

numbers.forEach((Integer number) -> {
    System.out.println(number);
});

In the above example, the forEach loop is called on the ArrayList “numbers”. The lambda expression (Integer number) -> { System.out.println(number); } specifies the operation to be performed on each element of the list. In this case, the lambda expression simply prints the integer value of each element.

The syntax for the lambda expression used in the forEach loop consists of the parameter list, the arrow operator ->, and the body of the lambda expression. The parameter list specifies the type and name of the parameter passed to the lambda expression. The arrow operator separates the parameter list from the body of the lambda expression. The body of the lambda expression specifies the operation to be performed on each element.

forEach() Signature in Iterable Interface:

The forEach() method is defined in the Iterable interface in Java. Here is the signature of the forEach() method in the Iterable interface:

void forEach(Consumer<? super T> action)

In the above signature, T represents the type of elements in the Iterable, and action is a Consumer functional interface that accepts a single argument of type T and returns no result.

The forEach() method takes a Consumer functional interface as a parameter, which is used to perform the operation on each element of the Iterable. The Consumer interface represents an operation that accepts a single input argument and returns no result. The forEach() method calls the accept() method of the Consumer interface for each element in the Iterable, passing the element as the argument.

Here’s an example of using the forEach() method to iterate over a list of integers and print each element:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.forEach(num -> System.out.println(num));

In the above example, the forEach() method is called on the list of integers, and a lambda expression is passed as the argument to the forEach() method. The lambda expression prints each element of the list.

Java 8 forEach() example:

Sure, here’s an example of using the forEach() method introduced in Java 8:

Suppose you have a list of Person objects and you want to print the name of each person in the list. You can use the forEach() method to iterate over the list and print the name of each person.

Here’s how you can do it:

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

public class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 30));
        people.add(new Person("Charlie", 35));

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

In the above example, we create a list of Person objects and add three people to the list. Then we call the forEach() method on the list and pass a lambda expression as an argument to the method. The lambda expression prints the name of each person in the list.

The output of the above program will be:

Alice
Bob
Charlie

Java Stream forEachOrdered() Method:

The forEachOrdered() method is a terminal operation in Java streams that performs an action on each element of the stream in the order specified by the stream’s encounter order. It is similar to the forEach() method, but guarantees that the order of elements in the stream is preserved during iteration.

Here’s the syntax of the forEachOrdered() method:

void forEachOrdered(Consumer<? super T> action)

The forEachOrdered() method takes a Consumer functional interface as an argument, which represents the operation to be performed on each element of the stream. The Consumer interface has a single method accept() that takes an argument of type T and returns no result. The forEachOrdered() method calls the accept() method of the Consumer interface for each element in the stream, in the order specified by the stream’s encounter order.

Here’s an example of using the forEachOrdered() method on a stream of integers:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] numbers = { 1, 2, 3, 4, 5 };

        Arrays.stream(numbers)
              .map(num -> num * 2)
              .forEachOrdered(System.out::println);
    }
}

In the above example, we create an integer array numbers and use the Arrays.stream() method to convert the array into a stream. We then use the map() method to multiply each element of the stream by 2, and finally call the forEachOrdered() method to print each element of the stream in the order specified by the stream’s encounter order.

The output of the above program will be:

2
4
6
8
10

Java Stream forEachOrdered() Method Example:

Sure, here’s an example of using the forEachOrdered() method on a stream of strings:

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

public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("apple");
        words.add("banana");
        words.add("cherry");
        words.add("date");
        words.add("elderberry");

        words.stream()
             .filter(word -> word.length() > 4)
             .map(String::toUpperCase)
             .forEachOrdered(System.out::println);
    }
}

In the above example, we create a list of strings words and add five words to the list. We then use the stream() method to create a stream of the words, and use the filter() method to select only those words that have a length greater than 4. We then use the map() method to convert the selected words to uppercase, and finally call the forEachOrdered() method to print each word in the order specified by the stream’s encounter order.

The output of the above program will be:

BANANA
CHERRY
ELDERBERRY

Note that the words “apple” and “date” are not printed, because they do not have a length greater than 4.