Last Updated:

How the java loop for each works

How the java loop for each works

Starting with Java 8, you can iterate through a list or any collection without using any loop in Java. The new Stream class provides a forEach() method that is used to loop through all or selected list and map items.

The forEach() method has several advantages over a traditional for loop, for example, you can execute it in parallel by simply using a parallel thread instead of a normal thread. Because you're working in a thread, it also allows you to filter and map items. Once you're done with filtering and displaying, you can use forEach() to work on them.

You can even use a method reference and a lambda expression inside the forEach() method, which will result in clearer and more concise code. Let's look at some examples of forEach() in Java 8.

Now that you know a little bit about the forEach() method and Java 8, it's time to review some of the code examples and learn more about the forEach() method in JDK 8.

Iterate through all list items using forEach()

You can loop through all the elements using the iteration. The forEach() method, as shown below:

List<String> alphabets
= new ArrayList<>(Arrays.asList(aa, bbb, cat, dog)); alphabets.forEach(s ->System.out.println(s));

This code will print each item in the list, called alphabets. You can even replace the lambda expression with a method reference, because we pass the lambda parameter as it is to the
System.out.println() method, as shown below:

alphabets.forEach(System.out::println);

Now let's see if you want to add a comma between the two elements, then you can do it with lambda parameters as shown in the following example:

alphabets.forEach(s ->System.out.print(s + «,»));

By the way, now you can't use a reference to a method because we're doing something with lambda parameters. Let's look at another example of the forEach() method for performing item filtering. If you want to learn more about cycles in Java, the Complete Java Masterclass is the most comprehensive course for Java programmers.

Example filter and forEach()

 

One of the main features of the Stream API is its ability to filter items based on certain conditions. We've already seen a glimpse of the powerful Stream API feature in my previous post, how to use the Stream API in Java 8, here we'll see it again, but in the context of the forEach() method.

Let's now print only elements starting with "a", the following code will do it for you, startWith() is a method of the String class that returns true if the String starts with "a", or returns false. Once the list is filtered, the forEach() method displays all the items that begin with "a", as shown below:

alphabets. ()
.filter(s ->s.StartsWith(«a»))
.forEach(System.out::println);

That's cool, right? You can easily read the code, it's much easier than using an iterator or any other way to cycle through the list in Java.

Now let's filter out something that has a length greater than 2, for this we can use the length() function of the String class:

alphabets. ()
.filter(s ->s.length() > 2)
.forEach(System.out::println);

In addition to forEach, this is also a good example of using the filter method in Java 8 to filter or select a subset of items from a stream. You can read more about this in Java 8 Threadbooks using the Lambda Expressions course on Pluralsight, which provides a detailed explanation of the new features in Java 8.

Example of forEach() and map()

 

While you have both a basic and advanced example of using the forEach() method, first with a simple iteration for each element and then using the filter() method, let's look at another example of the forEach() method along with the map() function, which is another key functionality of the Stream API.

The Java 8 map() method allows you to convert one type to another, for example, in our first example we use map() to convert a list of strings into a list of integers, where each element represents the length of a string. Now let's derive the length of each line using the map() function:

alphabets. ()
.mapToInt(s ->s.length())
.forEach(System.out::println);

How about calculating the sum of the length of all the strings? you can do this by using fold operations such as sum(), as shown in the following example:

alphabets. ()
.mapToInt(s ->s.length())
.сумма();

These were some of the common but very useful examples of the Java 8 forEach() method, a new way to cycle through a list in Java. If you're feeling nostalgic, then don't forget about forloop's journey into Java, a summary of forloop from JDK 1 to JDK 8.

If you want to learn more about functional programming in Java 8 and the use of map, flatmap methods, then I suggest you take the Learn Java Functional Programming with Lambdas & Streams course on Udemy. This is a good course filled with good examples for learning about the key features of Java 8.

A program to use the forEach() function in Java 8

importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;

/**
* A Java program that shows how to use the forEach() statement in Java8.
* You can get hung up on a list, set, or any collection using this
* method. You can even do filtering and conversion and
* can run the loop in parallel.
*
*/
public class Java8Demo {


public static void main(String args[]) {

List<String> alphabets = new ArrayList<>(
Массивы.asList(«aa», «bbb», «cac», «dog»));

Loop through all elements using Iterable.MethodforEach()
alphabets.forEach(s ->System.out.println(s));

You can even replace the lambda expression with a reference to the // method
because we pass the lambda parameter as it is in
the // method
alphabets.forEach(System.out::p rintln);

you can even do something with the lambda parameter, such as adding a
comma alphabets.forEach(s ->System.out.print(s + ","));

There is another forEach() method in the Stream class that works
// onstream and allows you to use various stream methods, such as filter()
// map() etc

alphabets.stream().forEach(System.out::println);

let's now print only elms that begin with "a"
alphabets. ()
.filter(s ->s.StartsWith(«a»))
.forEach(System.out::println);

let's filter out only what is longer than 2
alphabets. ()
.filter(s ->s.length() > 2)
.forEach(System.out::p rintln);

now let's print the length of each line using map()
alphabets. ()
.mapToInt(s ->s.length())
.forEach(System.out::println);

how about calculating the sum of the length of the entire alphabets string
. ()
.mapToInt(s ->s.length())
.sum();

}

}

Difference between for and foreach loops

 

The for loop is the overall structure of repetition. This helps you iterate through an operator or set of statements in your program. The syntax for the for loop is as follows:

for(initialization, test expression, expression update){
// code inside a for loop

}

 

Foreach Cycle

 

A foreach loop is a convenient way to retrieve elements in an array or collection. It can be used as an alternative to the fora cycle. It's called a foreach loop because it iterates through each element of an array or collection. The syntax for the foreach loop is as follows:

for(data type item: collection){

code inside each loop

}

Important things to remember:

  1. forEach() is a terminal operation that means that after calling the forEach() method on a thread, you cannot call another method. This will eliminate run-time.
  2. When you call forEach() on a parallel thread, the iteration order is not guaranteed, but you can ensure that order by calling the forEachOrdered() method.
  3. In Java 8, there are two forEach() methods, one defined inside Iterable and the other inside the java.util.stream.Stream class. If the goal of forEach() is simply an iteration, then you can call it directly as list.forEach() or set.forEach(), but if you want to perform some operations, such as a filter or map, it is better to get the flow first, and then perform this operation and finally call the forEach() method.
  4. Using forEach() results in readable and cleaner code.

That's all about how to use forEach() in Java 8. By following these examples, you can easily speed up your work using the forEach() method. It is ideal for use with streaming and lambda expressions and allows you to write code without loops in Java.