Java forEach() Method Tutorial 🎯

beginner
19 min

Java forEach() Method Tutorial 🎯

Welcome to this comprehensive Java tutorial on the forEach() method! In this lesson, we'll explore the forEach() method, a useful tool that simplifies iterating over collections in Java. By the end of this tutorial, you'll have a solid understanding of this essential concept. 📝 Note: This lesson is suitable for both beginners and intermediate learners. Let's get started!

Understanding the Java forEach() Method 📝

The forEach() method is a part of the Iterable interface in Java and is used to iterate through each element of a collection (like an array, List, or Set) and perform a specified action on each element.

Why Use the forEach() Method? 💡 Pro Tip:

Using the forEach() method can help you write cleaner and more concise code, as it eliminates the need for traditional for-loops and allows for a more functional programming style.

Basic Example of Java forEach() Method 🎯

Let's look at a simple example to better understand how the forEach() method works:

java
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; // Using forEach() method Arrays.stream(numbers).forEach(number -> System.out.println(number)); } }

In this example, we have an array of integers called numbers. We use the Arrays.stream() method to create a Stream object from our array, which allows us to use various methods, including forEach(). The forEach() method takes a lambda expression (in this case, number -> System.out.println(number)) as an argument, which specifies the action to be performed on each element of the array.

When you run this code, you'll see the output:

1 2 3 4 5

Advanced Example of Java forEach() Method 🎯

Now, let's consider a more advanced example, where we filter and transform a list of strings:

java
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<String> words = Arrays.asList("Apple", "Banana", "Orange", "Grapes", "Mango"); // Using forEach() method to print only fruits with more than 6 letters words.stream() .filter(word -> word.length() > 6) .forEach(System.out::println); } }

In this example, we have a list of fruits named words. We use the stream() method to create a Stream object from our list, and then we filter the list to include only strings with more than 6 letters using the filter() method. Finally, we use the forEach() method to print the filtered list.

When you run this code, you'll see the output:

Mango

Java forEach() Method Quiz 📝 Note:

Quick Quiz
Question 1 of 1

What is the purpose of the forEach() method in Java?

Quick Quiz
Question 1 of 1

What is the benefit of using the forEach() method in Java compared to traditional for-loops?