Skip Top Navigation Bar

Lambda in Java

When Can Lambda Be Used

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:

Implementing Interface without Lambda

Consider the following Computations interface:

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

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

and similarly for MultiplyComputation:

To use these classes, we might write the following:

Try it in the Java Playground

Implementing Interface with Lambda

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.

The general form is:

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.

Try it in the Java Playground

  1. Predict the output of the code then test your prediction by running it in the Java Playground.
  2. Edit the code to change the values that are being passed as parameters to operation. How does this change the output?
  3. Add implementations for multiply and add. Provide sample calls with output to test your code.

Positive Difference

Let's try an example where the body of the method contains more than one statement, such as an if statement.

Let's implement operation to compute the positive difference.

Try it in the Java Playground

  1. Predict the output of the code then test your prediction by running it in the Java Playground.
  2. Edit the code to change the values that are being passed as parameters to operation. How does this change the output?

You can also use an if statement instead of the conditional operator.