×

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

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java Math asin() Method

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

1 minute read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.