ForEach() Method : Lambda Expressions & Method Reference

Definition of ForEach() Method

ForEach() Method

Due to Java 8 new features, that provides us java coders a method named forEach() to iterate the elements. forEach() method is defined in iterable and Stream interface. The collection classes which is the one that extends the iterable interface can use forEach loop to iterate elements. As a result you can pass lambda expressions as an argument in this method because it takes a single parameter which is a functional interface.

Therefore the Syntax for the method is shown below :
default void forEach(Consumer<super T>action)
And heres one example using the lambda expressions:

import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {

List<String> gamesList = new ArrayList<String>();


gamesList.add(“Football”);
gamesList.add(“Cricket”);
gamesList.add(“Chess”);
gamesList.add(“Hockey”);

                    System.out.println(“————Iterating by passing lambda expression————–“);

    gamesList.forEach(games -> System.out.println(games));

This will output :
————Iterating by passing lambda expression————–

Football
Cricket
Chess
Hockey

And here we’re finally using method reference

import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {

List<String> gamesList = new ArrayList<String>();

gamesList.add(“Football”);
gamesList.add(“Cricket”);
gamesList.add(“Chess”);
gamesList.add(“Hockey”);


                    System.out.println(“————Iterating by passing method reference————–“); 
gamesList.forEach(System.out::println);
}

This will output :

————Iterating by passing method reference————–

Football
Cricket
Chess
Hockey

See a lot of other things related to methods in craftingez6-coding

2 thoughts on “ForEach() Method : Lambda Expressions & Method Reference”

  1. you’re really a good webmaster. The web site loading speed is amazing. It seems that you are doing any unique trick. Also, The contents are masterpiece. you’ve done a excellent job on this topic!

Leave a Reply

Your email address will not be published. Required fields are marked *