Contents

A Quick Start Guide To Java Lambda Expression

Lambda expression is used as an implementation of an interface which has functional interface. Interface with only one abstract method is called functional interface.

Basics:

Runnable, ActionListener, Comparable are some of the examples of functional interfaces.

1
2
3
4
@FunctionalInterface
public interface CalcDistance {
   double distance(double n1, double n2);
}

Now, Lets implement this

1
2
3
4
5
6
class CalcDistanceImpl implements CalcDistance {
   
   @Override
   public double distance(double n1, double n2) {
    return n1-n2
   }

A Simple Use Case:

1
2
CalcDistanceImpl calcDistanceImpl = new CalcDistanceImpl();
calcDistanceImpl.distance(10.0,20.0); // output -10.0

A Custom Implemention of Functional Interface, we want distance always in +ve

1
2
3
4
5
6
CalcDistance calcDistance = new CalcDistanceImpl(){
 @Override
 Public double distance(double n1, double n2){
    return Math.abs(n1-n2);
 }
}

Lambda Syntax

| Argument List | Arrow Token | Body | | (int x, int y) | -> | x + y |

With Lambda Expression

1
2
3
CalcDistance calcDistance = (n1, n2) -> { return Math.abs(n1-n2) };
OR
CalcDistance calcDistance = (n1, n2) -> Math.abs(n1-n2);
  • A Functional interface is a interface that has a single abstract method in it.
  • Lambda expressions can only be used to implement functional interfaces
  • They are just tools to provide a clear and concise way to represent one method interface.

Lambda expressions has paved the way for the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. ( Stream, Collections )

For more info See: