Skip Top Navigation Bar

Lambda in Java

If like me, you have found Lambda to seem a little too much like magic, let me see if I can help you connect the dots like I did!

Lambda’s allow programmers to implement an interface that contains one abstract method, without having to write the full class. They consist of:

So, here are the key points for me:

Consider the following Computations interface:

public interface Computations { 
   public double operation(double first, double second); 
}

We could create classes AdditionComputation and MultiplyComputation as well as several others, such as:

public class AdditionComputation implements Computations { 
   @Override 
   public double operation(double first, double second) { 
      return first + second; 
   }
}

and similarly for MultiplyComputation:

public class MultiplyComputation implements Computations { 
   @Override 
   public double operation(double first, double second) { 
      return first * second; 
   }
}

To use these classes, we might write the following:

public class LambdaTester { 
   public static void main(String[] args) { 
      AdditionComputation add = new AdditionComputation(); 
      MultiplyComputation mult = new MultiplyComputation(); 
      System.out.println(add.operation(5.3, 2.3)); 
      System.out.println(mult.operation(5, 3)); 
   }
}

Every time we wanted to provide unique functionality for the operation method in Computations, we would need to:

  1. create a class that implements Computations
  2. create an instance of this class
  3. call the method operation

With lambdas, we can create an instance of Computations that can be used to call the operation method and provide the functionality as part of declaring and creating that instance.

Consider implementing an operation method to subtract two values. We can create an instance, for example called subt, and use lambda to provide the implementation of the operation method as follows:

Computations subt = (f, s) -> f - s;
System.out.println(subt.operation(3,2));

Another example of using lambda is the forEach method of the ArrayList class. This method takes a Consumer object as a parameter. Consumer is an interface that has an accept method that needs to be implemented. The accept method performs an operation on the given argument. The following example passes the implementation of the method accept as an argument to the forEach method. For example, names is an ArrayList of String values:

names.forEach( (n) -> { 
   if (n.length() > 4) { 
      System.out.println(n); 
   }
} );

If you shared in my confusion of lambda’s, I hope this has helped make them more understandable and less magical.

Resources

Calculator - Using Conditionals and Lambda Mini-Lab

For more information on Lambda, check out these resources.