Code With Clarity

Java 8

Agenda


Lambda Expression (Anonymous Function)

A Lambda Expression is a function that does not have:

  • Name
  • Return type
  • Access modifier

Example:

public int m() {
}

In a lambda expression, we remove:

  • Method name (m)
  • Return type (int)
  • Access modifier (public)

After removing them:

() {}

To convert it into a lambda expression, we use the arrow operator (->):

() -> {};

Note: Semicolon (;) is mandatory for lambda expressions.


Important Points to Remember

  1. Parameter type is optional. Compiler automatically detects it (Type Inference).
  2. If there is only one parameter, brackets () are optional.
  3. If there is only one statement, curly braces {} are optional.
  4. If {} is removed, then return keyword must also be removed.
  5. If there is no parameter, brackets () are mandatory.
  6. If there are multiple parameters, brackets () are mandatory.

Lambda Examples

Example 1:

public int add(int a, int b) {
  return a + b;
}
(a, b) -> { return a + b; }   // valid
(a, b) -> a + b              // valid
(a, b) -> return a + b;      // invalid
a, b -> { return a + b; }    // invalid

Example 2:

public void method(int a) {
}
a -> System.out.println(a);

Example 3:

public void methodOne() {
}
() -> System.out.println("Anu");

Functional Interface

A Functional Interface is an interface that:

  • Has only one abstract method
  • Can have any number of default methods
  • Can have any number of static methods

Example:

public interface InterF {
  void m();
  
  default void m2() {}
  static void m3() {}
}

Invoking Lambda Using Functional Interface

InterF f = () -> System.out.println("Hello Lambda");
f.m();
public class Test {
  public static void main(String[] args) {
    InterF f = () -> System.out.println("Hello Lambda");
    f.m();
  }
}

Java 8 introduced @FunctionalInterface annotation to ensure that an interface has only one abstract method.

Invalid Example:

@FunctionalInterface
public interface InterF {
  void m1();
  void m2();  // Compilation error
}

Functional Interface and Inheritance

If a child interface does not add any new abstract method, it remains a Functional Interface.

@FunctionalInterface
public interface InterA {
  void m1();
}

@FunctionalInterface
public interface InterB extends InterA {
  void m1();  // Valid
}

Invalid Case:

@FunctionalInterface
public interface InterB extends InterA {
  void m2();  // Compilation error
}

If @FunctionalInterface is not used, then the interface can have multiple abstract methods.


Happy Coding 😊

Source Code: https://github.com/mahendrakr/java8