Lamba expression – an anonymous function that can be passed to or returned from a method. The most simple case of a lambda is a functional interface with a single method which receives some values and return a value. Actually any interface with a single abstract method can be treated as functional interface. Its implementation is called Lambda expression. So it is like a flavour of functional programming in Java 🙂

**Example**

So here is how shall we proceed to leverage Lamba expressions. We’ll implement a use case, which squares and cubes provided number:

- Create a functional interface for mathematical operation

public interface Operation{ int doOperation(int a); }

- Create a method, which takes functional interface as a parameter

private int doMath(int a, Operation op) { return Operation.doOperation(a); }

- Create Lamba expressions, which do actual mathematical operations

Operation square = a -> a * a; Operation cube = a -> a * a * a;

- Put all together into class
*LambdaSample*and test it

public class LambdaSample { public interface Operation { int doOperation(int a); } private int doMath(int a, Operation op) { return op.doOperation(a); } public static void main(String args[]) { LambdaSample sample = new LambdaSample(); Operation square = a -> a * a; Operation cube = a -> a * a * a; System.out.println("Square of 5: " + sample.doMath(5, square)); System.out.println("Cube of 5: " + sample.doMath(5, cube)); } }

Here is another sample of the same use case, just without explicitly declaring functional interface. Here we just switch from primitive type *int* to *Integer*, because primitive types are not allowed in generic type declarations.

import java.util.function.Function; public class LambdaSample { private int doMath(int a, Function<Integer, Integer> fnc) { return ((Integer) fnc.apply(a)).intValue(); } public static void main(String args[]) { LambdaSample sample = new LambdaSample(); Function<Integer, Integer> square = a -> a * a; Function<Integer, Integer> cube = a -> a * a * a; System.out.println("Square of 5: " + sample.doMath(5, square)); System.out.println("Cube of 5: " + sample.doMath(5, cube)); } }

Here I’ve defined just the very essence and the most simple sample. For comprehensive information, please check Java8 documentation here.

## 1 thought on “What is Lambda expression in Java8? Quick explanation and Sample.”

Comments are closed.