forEach loop in Java 8

In java foreach is introduced with the stream to iterate the stream. In this post, we will see how we can use for loop in java 8 and java stream foreach.

Here is the table content of the article will we will cover this topic.

1. What is forEach() method in Java?
2. Using forEach() in user-defined class?
3. Using forEach() in Stream?
4. Using ForEach() with Map?

What is java foreach() method in Java?

The forEach() method is defined in Iterable Interface and also declared in Stream Interface.
The Iterable Interface provides the default implementation of forEach(), So it is available for collections because Collection implements the Iterable interface.

default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

The Stream interface is just declaring the forEach() method. The implements will be provided during the use of Streams.

void forEach(Consumer<? super T> action);

The forEach() method works as a utility method that helps to iterate over a collection or stream. The forEach() method accepts the reference of Consumer Interface and performs a certain action on each element of it which define in Consumer.
As you can see forEach() accepts reference of Consumer that is action. The action will be provided by a class that implements the Consumer interface and is passed to forEach as an argument.

java foreach

Let’s understand with anonymous class. As you know forEach() method accepts an action of Consumer type. So, first of all, we will create an action that will be acceptable by forEach().

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ExampleOfForEach 
{
	public static void main(String[] args) 
	{
		Consumer<String> action = new Consumer<String>() 
		{
			@Override
			public void accept(String s) 
			{
				System.out.println("ForEach by anonymous class:"+ s);
				
			}
		};
		
		List<String> names = Arrays.asList("Ram","Sham","Mohan");
		names.forEach(action);
		
	}			
}

Output: ForEach by anonymous class:Ram
ForEach by anonymous class:Sham
ForEach by anonymous class:Mohan

As you can see in the above example, we defined an action that prints some statements. After that, we created an ArrayList of String types that contains some names. By using of forEach() method we print each element of the list along with a statement defined in action.

We can reduce this code by use of lambda expression. As you already know lambda expression can provide the implementation to Functional interface. The consumer is a functional interface so we can use a lambda expression.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ExampleOfForEach 
{
	public static void main(String[] args) 
	{
		Consumer<String> action = (s) ->	System.out.println("ForEach by Lambda expression:"+ s);
		List<String> names = Arrays.asList("Ram","Sham","Mohan");
		names.forEach(action);
		
	}			
}

Output:ForEach by Lambda expression:Ram
ForEach by Lambda expression:Sham
ForEach by Lambda expression:Mohan

Using java forEach() in user-defined class

public class Student 
{
	int rollNo;
	String className;
	String name;
	
	public Student(int rollNo, String className, String name) 
	{
		this.rollNo = rollNo;
		this.className = className;
		this.name = name;
	}
	public int getRollNo() 
	{
		return rollNo;
	}
	public void setRollNo(int rollNo) 
	{
		this.rollNo = rollNo;
	}
	public String getClassName() 
	{
		return className;
	}
	public void setClassName(String className) 
	{
		this.className = className;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ExampleOfForEach 
{
	public static void main(String[] args) 
	{
		Consumer<Student> action = (student) ->
		{
			System.out.println("Student name:"+ student.getName());
			System.out.println("Student Class:"+ student.getClassName());
			System.out.println("Student RollNo:"+ student.getRollNo());
		};
		List<Student> names = new ArrayList<Student>();
		names.add(new Student(101, "BCA", "KK"));
		names.add(new Student(108, "MCA", "HR"));
		names.add(new Student(107, "BCA", "MO"));
		
		names.forEach(action);
	}		
}

Output: Student name:KK
Student Class:BCA
Student RollNo:101
Student name:HR
Student Class:MCA
Student RollNo:108
Student name:MO
Student Class:BCA
Student RollNo:107

If you don’t want to create a reference for Consumer. You can assign action directly to the forEach() method.

import java.util.ArrayList;
import java.util.List;

public class ExampleOfForEach 
{
	public static void main(String[] args) 
	{
		List<Student> names = new ArrayList<Student>();
		names.add(new Student(101, "BCA", "KK"));
		names.add(new Student(108, "MCA", "HR"));
		names.add(new Student(107, "BCA", "MO"));
		
		names.forEach((student) ->
		{
			System.out.println("Student name:"+ student.getName());
			System.out.println("Student Class:"+ student.getClassName());
			System.out.println("Student RollNo:"+ student.getRollNo());
		});
		
	}		
		
}

Output: Student name:KK
Student Class:BCA
Student RollNo:101
Student name:HR
Student Class:MCA
Student RollNo:108
Student name:MO
Student Class:BCA
Student RollNo:107

Using forEach() in Stream

import java.util.ArrayList;
import java.util.List;

public class ExampleOfForEach 
{
	public static void main(String[] args) 
	{
		List<Student> names = new ArrayList<Student>();
		names.add(new Student(101, "BCA", "KK"));
		names.add(new Student(108, "MCA", "HR"));
		names.add(new Student(107, "BCA", "MO"));
		
		names.stream().forEach((student) ->
		{
			System.out.println("Student name:"+ student.getName());
			System.out.println("Student Class:"+ student.getClassName());
			System.out.println("Student RollNo:"+ student.getRollNo());
		});
		
	}		
		
}

Output: Student name:KK
Student Class:BCA
Student RollNo:101
Student name: HR
Student Class:MCA
Student RollNo:108
Student name:MO
Student Class:BCA
Student RollNo:107

Using ForEach() with Map

import java.util.HashMap;
import java.util.Map;

public class ExampleOfForEach 
{
	public static void main(String[] args) 
	{
		Map<Integer, String> mapOfWords = new HashMap<Integer, String>();
		mapOfWords.put(1, "Hi");
		mapOfWords.put(8, "Hello");
		mapOfWords.put(5, "Hye");
		mapOfWords.put(2, "Bye");
		
		mapOfWords.keySet().forEach((name) ->
		{
			System.out.println("Words from Map:"+ name);
		});
	}			
}

Output: Words from Map:1
Words from Map:2
Words from Map:5
Words from Map:8

Leave a Comment