Java forEach

 Java, forEach is a method introduced in Java 8 in the Iterable interface. It's a part of the Stream API and provides a way to iterate over elements of a collection and perform an action on each element. It takes a functional interface as an argument, typically a lambda expression or a method reference, which represents the action to be performed on each element.

Here's the syntax of forEach method:

void forEach(Consumer<? super T> action)

Where:

  • action is the action to be performed for each element.
  • Consumer is a functional interface from the java.util.function package. It represents an operation that accepts a single input argument and returns no result.

Let's see some examples:

Example 1: Basic usage with ArrayList

import java.util.ArrayList; public class ForEachExample {
public static void main(String[] args) { ArrayList<String> names =
ArrayList<String> names = new ArrayList<>(); names.add(
names.add("Alice"); names.add(
names.add("Bob"); names.add(
names.add("Charlie");

// Using forEach to print each name
names.forEach(name -> System.out.println(name));
}
}

Example 2: Using method reference

import java.util.ArrayList; public class ForEachExample {
public static void main(String[] args) { ArrayList<Integer> numbers =
ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(
numbers.add(1); numbers.add(
numbers.add(2); numbers.add(
numbers.add(3);

// Using forEach with method reference to print each number
numbers.forEach(System.out::println);
}
}

Example 3: Modifying elements

import java.util.ArrayList; public class ForEachExample {
public static void main(String[] args) { ArrayList<Integer> numbers =
ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(
numbers.add(1); numbers.add(
numbers.add(2); numbers.add(
numbers.add(3);

// Using forEach to double each number
numbers.forEach(num -> System.out.println(num * 2)); } }
}
}


Example 4: Using custom functional interface

import java.util.ArrayList; import java.util.function.Consumer; public class ForEachExample {
public static void main(String[] args) { ArrayList<String> names =
ArrayList<String> names = new ArrayList<>(); names.add(
names.add("Alice"); names.add(
names.add("Bob"); names.add(
names.add("Charlie");

// Custom functional interface for printing names
Consumer<String> printName = name -> System.out.println("Name: " + name);

// Using forEach with custom functional interface
names.forEach(printName);
}
}

In each of these examples, the forEach method is used to iterate over the elements of a collection (ArrayList in these cases) and perform specific actions on each element.

It provides a concise and expressive way to perform operations on collections in Java.



Previous Post Next Post

Welcome, New Friend!

We're excited to have you here for the first time!

Enjoy your colorful journey with us!

Welcome Back!

Great to see you Again

If you like the content share to help someone

Thanks

Contact Form