Home > Java > javaTutorial > Fundamentals of lambda expressions

Fundamentals of lambda expressions

Susan Sarandon
Release: 2025-01-07 08:09:41
Original
703 people have browsed it

Fundamentos das expressões lambda

Syntax Elements

Lambda Operator (->)

Divides the lambda expression into two parts:

Left side: Parameter list.

Right side: Lambda body (actions or return).

  • Lambda Body Types:

Single expression: Directly returns the result of an expression.

Code block: Contains multiple instructions.

Examples of Lambda Expressions:

1) No parameters:

Example: () -> 98.6

  • Empty parameter list.

  • Returns a constant value 98.6 (type inferred as double).

  • Equivalent to method:
    double myMeth() {
    return 98.6;
    }

Example: () -> Math.random() * 100

  • Returns a pseudorandom number multiplied by 100.

2) With parameters:

Example: (n) -> 1.0 / n

  • Returns the reciprocal of n.

  • Parameter type usually inferred, but may be declared explicitly.

3) Return of Boolean values:

Example: (n) -> (n % 2) == 0

  • Returns true if n is even, false otherwise.

  • Simplified form (without parentheses in the parameter):
    n -> (n % 2) == 0.

Considerations

  • The return type of a lambda expression is automatically inferred.

  • Parentheses in parameters are optional for lambda expressions with a single parameter.

  • The book suggests using parentheses for consistency in style.

General Summary

  • The lambda expression simplifies the creation of anonymous methods.

  • Flexible in terms of parameters and return types.

  • Adopts a concise syntax to improve code readability and expressiveness.

The above is the detailed content of Fundamentals of lambda expressions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template