Understanding Java Lambda Expressions

Java Lambda Expressions, introduced in Java 8, allow you to write more concise and readable code. These expressions provide a powerful way to pass around blocks of code as objects, enabling efficient execution when needed.



Java Lambda Expressions

Lambda expressions were introduced in Java 8. They are concise blocks of code that can be passed around like objects and executed on demand.

Syntax

The basic syntax for a lambda expression with a single parameter:

Syntax

(parameter) -> expression

To use multiple parameters, wrap them in parentheses:

Syntax

(parameter1, parameter2) -> expression

For more complex operations, use a code block:

Syntax

(parameter1, parameter2) -> { code block }

Using Lambda Expressions

Lambda expressions are commonly used as arguments to functions:

Example

import java.util.ArrayList;

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

Lambda expressions can be stored in variables if they match a single-method interface:

Example

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

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

Using a lambda expression in a method requires a single-method interface as a parameter:

Example

interface StringFunction {
String run(String str);
}

public class Main {
public static void main(String[] args) {
StringFunction exclaim = (s) -> s + "!";
StringFunction ask = (s) -> s + "?";
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
}

public static void printFormatted(String str, StringFunction format) {
String result = format.run(str);
System.out.println(result);
}
}