×

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java.

foreach loop in Java

Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended for loop. It offers a different method for traversing an array or collection in Java. It mostly serves to iterate through an array or collection of elements. The for-each loop has the benefit of making the code more understandable and removing the risk of problems. The for-each loop is so named because it goes through each element one at a time.

The extended for loop's disadvantage is that it is unable to iterate through the elements in reverse. Since it doesn't operate on an index basis in this case, you are unable to skip any elements. Additionally, you cannot only move through the odd or even elements.

However, because it makes the code more understandable, it is advised to utilize Java for-each loop when it comes to iterating through the elements of an array or collection. The code is easier to read as a result. It takes away the chance of programming mistakes.

Syntax

The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:), then array or collection.

for(data_type variable : array | collection){  
//body of for-each loop  
}  

Filename: ForEachExample1.java

//An example of Java for-each loop  
class ForEachExample1{  


  public static void main(String args[]){  
   //declaring an array  
   int arr[]={12,13,14,44};  
   //traversing the array with for-each loop  
   for(int i:arr){  
     System.out.println(i);  
   }  
 }   
}  

Let us see another Java for-each loop where we are going to total the elements.

Output

Java lambda foreach

Filename: ForEachExample1.java

class ForEachExample1{  
  public static void main(String args[]){  


   int arr[]={12,13,14,44};  
   int total=0;  
   for(int i:arr){  
     total=total+i;  
   }  
  System.out.println("Total: "+total);  
 }   
}  

Output

Java lambda foreach

For-each loop Example: Traversing the collection elements

Filename: ForEachExample2.java

import java.util.*;  
class ForEachExample2{  
  public static void main(String args[]){  
   //Creating a list of elements  
   ArrayList<String> list=new ArrayList<String>();  
   list.add("vimal");  
   list.add("sonoo");  
   list.add("ratan");  
   //traversing the list of elements using for-each loop  
   for(String s:list){  
     System.out.println(s);  
   }  
}   
}  

Lambda Expression

In Java 8, Lambda Expressions were introduced.

A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods, lambda expressions can be used directly in a method's body and do not require a name.

Syntax

A single parameter and an expression make up the simplest lambda expression.

parameter -> expression

Put parentheses around any other parameters you want to utilize.

(parameter1, parameter2) -> expression

Use a lambda expression in the ArrayList's forEach() method to print every item in the list:

Filename:Main.java

import java.util.ArrayList;


public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    numbers.forEach( (n) -> { System.out.println(n); } );
  }
}

Output

Java lambda foreach

If a variable's type is an interface with only one method, lambda expressions may be placed in those variables. The return type and parameter count for the lambda expression should match those of the corresponding method. Many of these interfaces are already included in Java, such as the Consumer interface used by lists (included in the java.util package).

In order to save a lambda expression in a variable, use Java's Consumer interface:

Filename:Main.java

import java.util.ArrayList;
import java.util.function.Consumer;


public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    Consumer<Integer> method = (n) -> { System.out.println(n); };
    numbers.forEach( method );
  }
}

Output

Java lambda foreach

The method must contain a parameter whose type is a single-method interface in order to employ a lambda expression. The interface's method will be used to execute the lambda expression:

Filename: Main.java

Make a method that accepts a parameter that is a lambda expression:

interface StringFunction {

  String run(String str);

import java.util.ArrayList;
import java.util.function.Consumer;


public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    Consumer<Integer> method = (n) -> { System.out.println(n); };
    numbers.forEach( method );
  }
}

Output

Java lambda foreach

The major benefit of Java 8 functional interfaces is that we can use Lambda expressions to instantiate them and avoid using bulky anonymous class implementations.

Argument-list: It can be empty or non-empty as well.
Arrow notation/lambda notation: It is used to link arguments-list and body of expression.
Function-body: It contains expressions and statements for lambda expression.

Filename: LambdaExpressionExample.java

import java.util.ArrayList;
import java.util.List;
public class LambdaExpressionExample {
  public static void main(String args[]){
List<String> list=new ArrayList<String>();  
        list.add("Jai");  
        list.add("Vivek");  
        list.add("Mahesh");  
        list.add("Vishal");  
        list.add("Naren");  
        list.add("Hemant");  
        list.add("Vikas"); 
        list.add("Ajay"); 
 
        list.forEach(  
            (name)->System.out.println(name)  
        );  
  }
} 

Output

Java lambda foreach

Related Topics

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.