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!
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.
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.
Let's look at a simple example to better understand how the forEach() method works:
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
Now, let's consider a more advanced example, where we filter and transform a list of strings:
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
What is the purpose of the forEach() method in Java?
What is the benefit of using the forEach() method in Java compared to traditional for-loops?