6 Ways To Use forEach in Java

August 23, 2020

To use for each in Java, you need to use the syntax like

Let’s have a look at some more examples of forEach in Java.

 

1. forEach and list

Using forEach, you can conveniently iterate over elements in a list. Have a look at the example below

The last two lines show two ways to achieve the same result – printing elements of the list. The first one is a standard lambda expression. The second one is the so-called method reference.

Running this code will result in

 

2. forEach and array

Using forEach, you can also iterate over elements in an array.

As you can see, we used the syntax Arrays.stream(array).forEach(…). And we also used both lambda expression and method reference to print elements.

The result of running the code is:

 

3. forEach and map

This paragraph explains the usage of forEach and map.

As you can see in the last line of code, we used the lambda expression with two parameters id and name.

Result of executing the code is:

 

4. Using forEach with consumer

When using forEach, you can pass as a parameter to it a consumer. Let’s have a look at the example below.

Executing the code will print to the console:

 

5. Using forEach with streams

You can also use forEach when working with streams.

In the example above, we firstly created a list of integers from 1 to 6. After that, we filtered numbers greater than 3. And lastly, we printed them to the console.

Running this code will print:

 

6. forEach and Collection interface

You can also use forEach with the Collection interface.

Executing the code will print

Click here to add a comment

Leave a comment: