×

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

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.