HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

7) Lambda Expressions & Methods References Lesson

Java Lambda Expressions

11 min to complete · By Ryan Desmond

Java 8 brought a powerful new syntactic improvement in the form of lambda expressions.

Three university men looking forward with a look of disbelief.

What is a Lambda Expression

A lambda expression is an anonymous function that can be passed to or returned from a method. It can be created without belonging to any class, and it can be used as an object as well as executed on demand.

One of the greatest benefits of using a lambda function is the simplicity of its syntax.

Benefits of Lambdas

Lambda expressions provide a clear and concise way to represent a one-method interface (aka Functional Interface) using an expression. Lambda expressions also improve the Collection libraries, making it easier to iterate through, filter, and extract data from a Collection

Before Java 8, you would usually create a class for every case where you needed to encapsulate a single piece of functionality. This implied a lot of unnecessary boilerplate code to define something that served as a primitive function representation. (As you saw in the previous primer on anonymous inner classes.)

Info: The word boilerplate is used by programmers to describe a code template that is used as a starting point, which saves time by providing proper syntax and repeated code. For example, at the end of this article, there is a boilerplate for a lambda function.

How to Write a Lambda Expression

A lambda expression is an unnamed function with parameters and a body. They are used in conjunction with functional interfaces.

The lambda expression body can be a block statement or an expression on a single line. The lambda expression introduces a new piece of syntax: ->. This -> operator separates the parameters and the body of the function. 

The example below provides a class that incorporates several types of lambda functions.

public class Main {
  public static void main(String[] args) {

    // lambda that takes an int parameter and 
    // returns the parameter value incremented by 1.
    SomeFunctionalInterface obj = (int x) -> x + 1; 
    int a = obj.singleInterfaceMethod(5);
    System.out.println(a);

    // lambda that takes two int parameters and returns the sum.
    SomeOtherFunctionalInterface obj1 = (int x, int y) -> x + y;
    int b = obj1.singleInterfaceMethod(4, 19);
    System.out.println(b);

    // lambda that takes a String parameter and 
    // prints it on the standard output.
    SomeOtherFunctionalInterface obj2 = (String msg) -> {
      System.out.println(msg);
    };         
    obj2.singleInterfaceMethod("Hello Lambda!");
      
    // lambda that takes a parameter and prints 
    // it on the standard output - equivalent to above
    SomeOtherFunctionalInterface obj3 = 
      msg -> System.out.println(msg);
    obj3.singleInterfaceMethod("Yay!");

    // lambda that takes no parameters and returns a string.
    SomeOtherFunctionalInterface obj4 = () -> "hi";
    obj4.singleInterfaceMethod("Lambda!");

    // lambda that takes a String parameter and returns its length.
    SomeOtherFunctionalInterface obj5 = 
      (String str) -> str.length();
    int phraseLength = 
      obj5.singleInterfaceMethod("Programming is cool!");
    System.out.println(phraseLength);

    // lambda takes two int parameters and 
    // returns the maximum of the two.  
    SomeOtherFunctionalInterface obj6 = (int x, int y)  ->  {  
      int max = x  > y  ?  x  : y;  
      return max;  
    };

    int largerNumber = obj6.singleInterfaceMethod(32, 87);
    System.out.println(largerNumber);
  }
} 

Lambda Expression Examples

Practice makes perfect! Below, you will find three examples of using lambdas in different ways.

Set a Lambda to a Variable

In this example, you'll set a variable's value to a lambda expression.

// A sample functional interface 
// (An interface with a single abstract method (SAM)
interface FunctionalInterface { 
  // An abstract function 
  void abstractFunction(int x); 
} 

class Main { 
  public static void main(String args[])  { 
    // lambda expression to implement the 
    // above functional interface. 
    FunctionalInterface lambda = 
        (int x) -> System.out.println(x * 2); 

    // This invokes the lambda expression and prints 10
    lambda.abstractFunction(5); 

    // redefine the lambda
    lambda = (int x) -> System.out.println(x * x); 

    // This invokes the lambda expression and prints 25  
    lambda.abstractFunction(5); 
  } 
} 

Lambda Expression with No Parameter

While lambda expressions are often created with parameters, they are not required.

//  Java Lambda Expression with no parameter
@FunctionalInterface  
interface MyFunctionalInterface {  
  // A method with no parameter
  public String sayHello();  
} 
 
public class Main {     
  public static void main(String args[]) {  
    // lambda expression
    MyFunctionalInterface msg = () -> {  
      return "Hello";  
    };  

    // This will print "Hello"
    System.out.println(msg.sayHello());  
  }  
}

Passing a Lambda as a Method Parameter

In Java, lambdas are so easy to process that they can be passed as parameters to methods.

interface FuncInterface {  
  int operation(int a, int b);  
}  
  
class Main {  
  private int operate(int a, int b, FuncInterface fobj)  {   
    return fobj.operation(a, b); 
  } 

  public static void main(String args[]) { 
    FuncInterface add = (int x, int y) -> x + y;
    FuncInterface multiply = (int x, int y) -> x * y; 
    Main obj = new Main(); 

    // Add two numbers using lambda expression 
    System.out.println("Addition is " + obj.operate(6, 3, add)); 

    // Multiply two numbers using lambda expression 
    System.out.println("Multiplication is " + obj.operate(6, 3, multiply)); 
  }   
} 

List Processing with Lambdas

Java 8 also introduced the forEach() method to the ArrayList class, which will iterate over every element in a list and perform a desired action. If you missed your introduction to the foreach() method, then check out this article.

The action that is performed is determined by the lambda expression that you pass into the forEach() method.  

import java.util.ArrayList; 

class Main { 
  public static void main(String args[]) { 

    ArrayList<Integer> nums = new ArrayList<Integer>();   
    nums.add(65); 
    nums.add(44); 
    nums.add(189); 
    nums.add(88); 

    // lambda to print all elements 
    nums.forEach(n -> System.out.println(n)); 

    // lambda to print odd elements 
    nums.forEach(n -> { 
      if (n%2 != 0) 
        System.out.println(n + " is odd"); 
    }); 
  } 
} 

This is a lot of information, but stay tuned for the videos, which go into depth and cover a lot of the things that were introduced in the past couple of articles. You got this!

Summary: Java Lambda Expression

  • A lambda expression is an anonymous function
  • Lambda expressions can be created without belonging to a class
  • Lambdas were introduced in Java 8
  • The -> operator separates a lambda's parameters from the method body
  • Lambdas can be used inside of forEach() method

Provided Lambda Examples

  • Set a Lambda to a Variable
  • Lambda Expression with No Parameter
  • Passing a Lambda as a Method Parameter
  • List Processing with Lambdas

Syntax

Here's the syntax for creating a lambda expression in Java, where you can substitute the variables starting with your_ with your values and add as many parameters as you'd like.

your_variable = (your_type your_parameter -> your_method_body)