×

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

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.