Java 8 Lambda : an example

There is no equivalent to c++ function pointers in Java. Which means that it is not possible to pass a method as a parameter to another method (unless reflection is used but I wont go there)… you can pass an interface instead though.

For example – given two different methods add and multiply:

int add(int f1, int f2){
        return f1+f2;

int multiply(int f1, int f2){
        return f1*f2;

…and a method which accepts a Calculator interface as its parameter

interface Calculator {
    public int calculate(int i,int j);

void recordCalc(Calculator calculator, int i, int j){
           int result =calculator.calculate(i,j);
           // the result on disk

then passing add(i,j) or multiply(i,j) as a parameter to the recordCalc method is done like so:

Calculator add = new Calculator(){
   public int calculate(int i, int j) {
      return add(i,j);
} ;

Calculator multiply = new Calculator(){
   public int calculate(int i, int j) {
      return multiply(i,j);
} ;


ie. we create two anonymous classes, each implementing Calculator in their own way, which are then passed to the recordCalc method as an interface. It is a bit ugly there’s no denying it.

Enter stage left: Java 8 with lambda support. A lambda is basically a very compact way to implement anonymous classes. They’re represented using an arrow “->”, like so:

    Calculator add = (i, j) -> add(i,j);
    Calculator multiply = (i, j) -> multiply(i, j);
    recordCalc(multiply, 3, 3);
    recordCalc(add, 5, 5);

or even simpler

   recordCalc((i, j) -> add(i,j), 3, 3);
   recordCalc((i, j) -> multiply(i, j), 5, 5);

The initial 16 lines of code implementation using anonymous classes is now reduced to a 2-liner. Shame it’s another 6 months to wait before Java 8 is officially released.

Finally – if you’re using IntelliJ an anonymous class can be transformed into a lambda with one click of the mouse:

IntelliJ lambda conversion


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s