Java 8 forEach() method defined in Iterable interface. It is used to iterate over collections such as Sets, Lists, and Maps in a readable and concise way. It was introduced as part of the functional programming features in Java 8, allows us to directly pass actions such as Method references or Lambda expressions. Instead of writing long loops, we can use forEach() along with a lambda expression to perform operations on each element.
The following Java program demonstrates how to use Java 8's forEach() method with a lambda expression to iterate through an ArrayList.
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
// main method
public static void main(String[] args) {
List gamesList = new ArrayList(); // Creating a new ArrayList to store games
// Adding games to the list
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hockey");
// Printing a separator
System.out.println("------------Iterating by passing lambda expression--------------");
// Iterating over the list using forEach and printing each element using a lambda expression
gamesList.forEach(game -> System.out.println(game));
}
}
Output:
------------Iterating by passing lambda expression-------------- Football Cricket Chess Hocky
The following Java program demonstrates how to use a HashMap and the forEach() method with a lambda expression to iterate through all key-value pairs.
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
// main method
public static void main(String[] args) {
// creating a HashMap
Map map = new HashMap<>();
map.put("A1", 110);
map.put("B1", 210);
map.put("C1", 310);
map.put("D1", 410);
map.put("E1", 510);
map.put("F1", 610);
// for each using lambda
map.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
}
}
Output:
Key : A1, Value : 110 Key : F1, Value : 610 Key : E1, Value : 510 Key : D1, Value : 410 Key : C1, Value : 310 Key : B1, Value : 210
This Java program demonstrates how to use a Consumer functional interface with both a List and a Stream to convert strings into their hexadecimal character representations.
Java
import java.util.function.Consumer;
import java.util.*;
import java.util.stream.Stream;
public class Main {
// main method
public static void main(String[] args) {
List list1 = Arrays.asList("def", "Python", "Java");
Stream stream1 = Stream.of("def", "Python", "Java");
// convert a String to a Hexadecimal
Consumer displayTextInHexConsmer = (String s) -> {
StringBuilder sbObj = new StringBuilder();
for (char ch : s.toCharArray()) {
String h = Integer.toHexString(ch);
sbObj.append(h);
}
System.out.print(String.format("%n%-10s:%s", s, sbObj.toString()));
};
// passing a Consumer
list1.forEach(displayTextInHexConsmer);
stream1.forEach(displayTextInHexConsmer);
}
}
Output:
def :646566 python :707974686f6e Java :6a617661 def :646566 Python :707974686f6e Java :6a617661
In this example, the forEach() method uses a method reference instead of a lambda expression.
Java
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List gamesList = new ArrayList();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hockey");
//iterating over list
gamesList.forEach(System.out::println);
}
}
Output:
Football Cricket Chess Hockey
| Feature | forEach() Method | Traditional Loop (for, while) |
|---|---|---|
| Paradigm | It is declarative (we state what to do). | It is imperative (we state how to do it). |
| Control Flow | It does not support break or continue statement. | It supports break, continue, and return statement. |
| Data Scope | It creates a new block scope for each callback. | It shares the same scope across all iterations. |
| Asynchronous Behavior | It does not wait for async/await promises. | It seamlessly supports async/await step-by-step. |
| Applicability | It is specific to arrays or collections. | It is used for general purpose. It can run without a collection. |
| Performance | It is slightly slower due to function call overhead. | It is faster, highly optimized by compilers. |
We request you to subscribe our newsletter for upcoming updates.