Java Lambda Syntax

beginner
15 min

Java Lambda Syntax

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Java Lambda Syntax. šŸŽ‰

Java Lambda expressions provide a concise syntax to define small, anonymous functions that can be used wherever a Functional Interface is required. Let's explore this powerful feature step by step.

Understanding Lambda Syntax

A Lambda expression is a block of code that represents an anonymous function. It consists of three main components:

  1. Parameters (enclosed in parentheses)
  2. Arrow token (->)
  3. Function body (enclosed in curly braces)

Here's a simple example of a Lambda expression:

java
(int num) -> { return num * num; }

In this example, int num are the parameters, -> is the arrow token, and { return num * num; } is the function body.

Functional Interfaces

For Lambda expressions to work, they must be assigned to a Functional Interface - an interface with exactly one abstract method.

Here's an example of a Functional Interface:

java
@FunctionalInterface interface SquareOfNumber { int square(int num); }

Using Lambda Expressions

Now that we've discussed Functional Interfaces, let's see how we can use Lambda expressions to solve real-world problems.

java
SquareOfNumber squareOfNumber = (int num) -> { return num * num; }; System.out.println(squareOfNumber.square(5)); // Output: 25

In this example, we created a SquareOfNumber Functional Interface and assigned a Lambda expression to it. We then called the square method to calculate the square of 5.

šŸ’” Pro Tip: Lambda expressions can make your code more readable and less cluttered, especially when working with collections, events, and network calls.

Lambda Expression Types

Lambda expressions can be of four types, depending on the number of parameters and the return type:

  1. (int a) -> int - Single-parameter, no return statement
  2. (int a, int b) -> int - Two or more parameters, no return statement
  3. (int a) -> void - Single-parameter, with return statement
  4. (int a, int b) -> void - Two or more parameters, with return statement

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of Lambda expressions in Java?


Stay tuned for more exciting lessons on Java! If you're finding this tutorial helpful, consider sharing it with your fellow coders. šŸ’Ŗ

Happy coding! šŸŽÆ