Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Lambda expressions are a feature introduced in Java 8 that allows you to create anonymous functions. They provide a concise way to represent functional interfaces (interfaces with only one abstract method) using an expression. This tutorial will walk you through the basics of lambda expressions in Java.
A functional interface is an interface with a single abstract method. Here's an example of a functional interface:
@FunctionalInterface public interface MyFunction { int apply(int a, int b); }
A lambda expression consists of a list of parameters, a lambda operator (->), and a body. The body can be a single expression or a block of code enclosed in curly braces.
(parameters) -> expression
or
(parameters) -> { statements; }
To use a lambda expression, you can assign it to a variable of the functional interface type or pass it as an argument to a method.
Here's an example of assigning a lambda expression to a variable of the MyFunction
interface type:
MyFunction addition = (int a, int b) -> a + b; int sum = addition.apply(5, 3); // sum will be 8
Java's type inference allows you to omit the parameter types in a lambda expression if they can be inferred from the context.
MyFunction addition = (a, b) -> a + b;
Suppose we have a method that accepts a functional interface as an argument:
public static void performOperation(int a, int b, MyFunction operation) { System.out.println(operation.apply(a, b)); }
We can use a lambda expression to call this method:
performOperation(5, 3, (a, b) -> a * b); // Output: 15
Java provides some built-in functional interfaces, such as java.util.function.Predicate
, java.util.function.Consumer
, and java.util.function.Function
. You can use lambda expressions with these interfaces as well.
For example, using the Predicate
interface:
import java.util.function.Predicate; public class LambdaDemo { public static void main(String[] args) { Predicate<Integer> isEven = n -> n % 2 == 0; System.out.println(isEven.test(4)); // Output: true } }
This tutorial covered the basics of lambda expressions in Java, including functional interfaces, lambda expression syntax, type inference, and using lambda expressions with built-in functional interfaces. Lambda expressions provide a more concise and flexible way to work with functional interfaces and can make your code more readable and expressive.
Functional interfaces and Lambda Expressions in Java
Functional interfaces have a single abstract method and can be used with lambda expressions.
// Functional interface interface MyFunction { void myMethod(); } // Lambda expression MyFunction func = () -> System.out.println("Executing myMethod"); func.myMethod();
Lambda Expressions vs. anonymous classes in Java
Lambda expressions provide a more concise syntax compared to anonymous classes for functional interfaces.
// Anonymous class MyFunction anonymous = new MyFunction() { @Override public void myMethod() { System.out.println("Executing myMethod anonymously"); } }; // Lambda expression MyFunction lambda = () -> System.out.println("Executing myMethod with lambda");
Using Lambda Expressions for concise code in Java
Lambda expressions simplify code for functional interfaces.
// Before Lambda Runnable runnableBefore = new Runnable() { @Override public void run() { System.out.println("Running before Lambda"); } }; // With Lambda Runnable runnableLambda = () -> System.out.println("Running with Lambda");
Lambda Expressions and the Stream API in Java
Lambda expressions are commonly used with the Stream API for functional-style operations on sequences of elements.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Using Lambda with Stream API names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println);
Capturing variables in Lambda Expressions
Lambda expressions can capture and use variables from their enclosing scope.
int x = 10; MyFunction lambdaWithCapture = () -> { System.out.println("Value of x: " + x); };
Method references in Java Lambda Expressions
Method references provide a shorthand syntax for lambda expressions.
// Lambda expression Consumer<String> consumerLambda = s -> System.out.println(s); // Method reference Consumer<String> consumerReference = System.out::println;