Java 8 Lambda Expressions

Java Cody - java 8 lambda Expressions

Java 8 Lambda expressions represent a significant improvement in the way you write code in Java, particularly when working with collections and functional interfaces. Lambda expressions allow you to treat functionality as a method argument or to create a more concise way of writing code, especially in places where you would traditionally use anonymous inner classes.

Definition of a Lambda Expressions ?

A lambda expressions in Java is a short block of code that takes in parameters and returns a value. It’s often used to implement the method defined in a functional interface.

Syntax : (parameters) -> expression

For example, the following lambda expression takes two integers and returns their sum:

(int a, int b) -> a + b;

Components of a Lambda Expression


(parameters) -> expression

  1. Parameter List: This is the list of parameters, similar to what you would use in a method. It’s enclosed in parentheses. If there are no parameters, you use empty parentheses. Example: (a, b) or ()
  2. Arrow Token (->): This separates the parameters from the body of the lambda expression.
  3. Body: The body of the lambda expression can either be a single expression or a block of statements. If it is a single expression, you don’t need to explicitly write a return statement.

//Example of a single expression:
 a -> a * 2
//Example with a block:
(a, b) -> {
    int result = a + b;
    return result;
}

Learn more on other Java 8 Features

Why use Lambda Expression ?

  • Concise Code: Lambda expressions reduce boilerplate code. Instead of writing anonymous classes, you can directly define the implementation.
  • Functional Style: They enable functional programming techniques, such as passing behavior as arguments to methods.
  • Enhanced Readability: They can make code more readable by eliminating the verbosity of anonymous inner classes.
Without Lambda expressions, Java requires using anonymous classes to implement interfaces with single methods, making code verbose.

Example without Lambda Expression (Using Anonymous Class)


//Example Without Lambda (Using Anonymous Class)

interface MyInterface {
    void show();
}

public class WithoutLambda {
    public static void main(String[] args) {
        MyInterface obj = new MyInterface() {
            @Override
            public void show() {
                System.out.println("Hello from Anonymous Class");
            }
        };
        obj.show();
    }
}
Output:
Hello from Anonymous Class


Example using Lambda Expression


// Using Lambda Expression
//Using Lambda expressions, the above code simplifies as:

interface MyInterface {
    void show();
}

public class WithLambda {
    public static void main(String[] args) {
        MyInterface obj = () -> System.out.println("Hello from Lambda!");
        obj.show();
    }
}
Output:
Hello from Lambda!


Types of Lambda Expression

A. Lambda Expression with No Parameters


//Lambda Expression with No Parameters
@FunctionalInterface
interface MyFunctionalInterface {
    void display();
}

public class LambdaExample {
    public static void main(String[] args) {
        MyFunctionalInterface obj = () -> System.out.println("Lambda with no parameters");
        obj.display();
    }
}
//No need for method implementation in a separate class

B. Lambda Expression with One Parameter


//Lambda Expression with One Parameter
@FunctionalInterface
interface Greeting {
    void sayHello(String name);
}

public class LambdaOneParameter {
    public static void main(String[] args) {
        Greeting greet = (name) -> System.out.println("Hello, " + name);
        greet.sayHello("Alice");
    }
}
Output:
Hello, Alice
//No need for braces `{}` if only one statement is present 


C. Lambda Expression with Multiple Parameters


//Lambda Expression with Multiple Parameters
@FunctionalInterface
interface MathOperation {
    int add(int a, int b);
}

public class LambdaMultipleParameters {
    public static void main(String[] args) {
        MathOperation sum = (a, b) -> a + b;
        System.out.println("Sum: " + sum.add(10, 20));
    }
}
Output:
Sum: 30
//No need for `return` or `{}` if it's a single statement 


D. Using Lambda with Functional Interfaces


//Lambda expressions work with functional interfaces(interfaces with a single abstract method).

//Java’s Built-in Functional Interface (Runnable)
public class LambdaRunnable {
    public static void main(String[] args) {
        Runnable r = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Running Thread " + i);
            }
        };
        Thread t = new Thread(r);
        t.start();
    }
}
Output: 
Running Thread 0
Running Thread 1
Running Thread 2
Running Thread 3
Running Thread 4

//Reduces boilerplate code


E. Using Lambda with Collections (Sorting & Filtering)


//Sorting a List using Lambda
import java.util.*;

public class LambdaSorting {
    public static void main(String[] args) {
        // Create a mutable list
        List<string> names = new ArrayList&lt;&gt;(Arrays.asList("John", "Jane", "Jack", "Alice"));
        // Sorting using Lambda
        names.sort((a, b) -&gt; a.compareTo(b));
        System.out.println(names);
    }
}
Output :
[Alice, Jack, Jane, John]
//More readable than traditional Comparator</string>

F. Filtering a List using Streams and Lambda


//Filtering a List using Streams and Lambda
import java.util.*;
import java.util.stream.*;

public class LambdaFilter {
    public static void main(String[] args) {
        List<string> names = Arrays.asList("Apple", "Banana", "Cherry", "Avocado");

        // Filtering names starting with 'A'
        List<string> result = names.stream()
                                   .filter(name -&gt; name.startsWith("A"))
                                   .collect(Collectors.toList());

        System.out.println(result);
    }
}
Output : 
[Apple, Avocado]
//Efficient filtering using Streams and Lambda 
</string></string>

G. Method References (Shorthand for Lambda)


//Method References (Shorthand for Lambda)
//Instead of writing a full Lambda, you can use Method References.
import java.util.*;

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<string> names = Arrays.asList("Apple", "Banana", "Cherry");

        // Using method reference instead of lambda
        names.forEach(System.out::println);
    }
}
Output :
Apple
Banana
Cherry
//method reference System.out::println, which refers to the println method of the System.out object.
</string>

H. Using Lambda in Custom Functional Interface


//Using Lambda in Custom Functional Interface
//Creating a Custom Functional Interface
@FunctionalInterface
interface MathOperation {
    int operate(int a, int b);
}

public class LambdaCustomInterface {
    public static void main(String[] args) {
        // Using Lambda for Addition
        MathOperation addition = (a, b) -&gt; a + b;
        
        System.out.println("Addition: " + addition.operate(5, 10));
    }
}
Output :
Addition: 15


Conclusion on Lambda Expressions

✔ Lambda Expressions reduce boilerplate code
✔ They make Java more functional and expressive
✔ They work best with Functional Interfaces
✔ Improves performance with parallel execution (Streams)

Java 8 Lambda Expressions Interview Questions

What is a Lambda Expression in Java?

A lambda expression is a feature introduced in Java 8 that enables you to treat functionality as a method argument. It is used to implement a method in a functional interface. It allows you to pass behavior as a parameter to methods.

Syntax:

(parameters) -> expression or block of code

Example:

(int a, int b) -> a + b

In this example, (int a, int b) are parameters, and a + b is the expression.

What are Functional Interfaces in Java 8?

A functional interface is an interface that contains exactly one abstract method. They can have multiple default or static methods. Functional interfaces can be implemented using lambda expressions or method references.

Some common functional interfaces in Java 8 are:

  • Runnable

  • Comparator

  • Predicate

  • Function

  • Consumer

  • Supplier


@FunctionalInterface
interface MyFunctionalInterface {
    void display();
}

How do Lambda Expressions differ from Anonymous Classes?(Lambda Expressions vs Anonymous classes)

Lambda Expressions:

  • Shorter and easier to read.

  • No need to create a new class.

  • Can use final or effectively final variables from the surrounding scope.

Anonymous Classes:

  • More code and less concise.

  • Requires declaring a new class.

  • Can access final or effectively final variables from the surrounding scope.

What is the use of the -> symbol in Lambda expressions?

The -> symbol is called the lambda operator or arrow operator. It separates the parameters (input) from the body (expression or code block) of the lambda expression. (a, b) -> a + b

Can a Lambda Expressions have multiple statements?

Yes, a lambda expression can have multiple statements. If it does, the body must be enclosed in curly braces {}. In this case, you will also need to use a return statement if the expression is meant to return a value.


(a, b) -&gt; {
    int sum = a + b;
    System.out.println("Sum: " + sum);
    return sum;

What is method reference in Java ?

Method reference is a shorthand notation of a lambda expression to call a method directly by referring to it using the class or instance. It uses the :: operator.


// Lambda expression
names.forEach(name -&gt; System.out.println(name));

// Method reference
names.forEach(System.out::println);

2 thoughts on “Java 8 Lambda Expressions”

  1. Pingback: Java 8 Features | Java 8 Features with Example - Java Cody

  2. Pingback: Functional Interface in Java - Java Cody

Leave a Comment

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

Scroll to Top