Lambda Expressions in Java 8

Functional Interface

  • A functional interface is any interface that contains only one abstract method
  • It may contain extra default or static methods

 Lambda Expressions

    • Treat functionality as method argument
    • It adds Functional behaviour to Java
    • It is basically an implementation of single abstract method in functional interface
    • Lambda expressions is preferred over Anonymous classes because later is bulky
    • JDK also has predefined standard Functional Interfaces e.g. Predicate

Example

Java predefined generic Predicate Interface (Functional Interface)

interface Predicate<T> {
    boolean test(T t);
}
  • Below method accepts Functional interface as input (Predicate in this case)
  • It then invokes one and only abstract method defined in the interface (test in this case)
  • Implementation of this abstract method is given by Lambda expression in following section
public static void displayStudentsOnCondition(
    // Predicate is generic interface
    List<Student> students, Predicate<Student> condition) {
    for (Student s : students) {
        // test method is declared in Predicate interface
        if (condition.test(s)) {
            System.out.println(s.toString());
        }
    }
}
  • Lambda expression is passed as parameter
  • Implementation of single abstract method in the functional interface is provided in Lambda expression
  • Arguments provided in the lambda expression are basically arguments to functional interface method (Predicate test in this case)
displayStudentsOnCondition(
    students,
    p -> p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25
)

Resources

Leave a Reply

Your email address will not be published. Required fields are marked *