Lambda Expressions in Java

Lambda Expressions in Java

In Functional Programming, one of the consequences of Functions becoming First Class Citizens, is that they are used more frequently and their life cycle is shorter.

This is why when using Functional Programming in Java, anonymous classes are much more frequently used as a mechanism to declare and pass around short-live anonymous functions.

However, because this approach is quite verbose, lambda expressions and method references were introduced in Java8 to simplify the syntax and enhance readability.

Let's see them in more detail.

Anonymous Classes

Anonymous classes are local classes without a name, typically for a one time use as a class that has a specific implementation of a subclass or interface.

import java.util.List;
import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);

        numbers.forEach(new Consumer<Integer>() {
            @Override
            public void accept(Integer n) {
                System.out.println(n);
            }
        });
    }
}        

Anonymous Functions

Anonymous functions are functions without a name, and just as anonymous classes, they are intended to serve a short-lived purpose.

Before Java8, there was no native way to define standalone functions, so developers often used anonymous classes as a workaround to encapsulate and pass functions.

Lambda expressions

Lambda expressions are a concise representation of anonymous functions, introduced in Java 8. They replace anonymous classes in many scenarios, making the code shorter and easier to read.

The basic syntax is

(parameter) -> expression
(parameter) -> { statements; }
(parameter1, parameter2) -> expression
(parameter1, parameter2) -> { statements; }        

In the following example, the lambda function `n -> System.out.println(n)` is used to print each element of the list.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Arrays.asList(1, 2, 3, 4, 5)
                .forEach(n -> System.out.println(n));
    }
}        

Method references

Method references were introduced in Java 8 as a more concise way to express a lambda expression to improve code readability, just by referring a method without explicitly invoking it using the `::` operator.

ClassName::methodName
instance::methodName        

Here we can find the same example as before, but using method reference.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Arrays.asList(1, 2, 3, 4, 5)
                .forEach(System.out::println);
    }
}        

要查看或添加评论,请登录

Jerónimo Calvo Sánchez的更多文章

  • Getting started with Java Stream API

    Getting started with Java Stream API

    Disclaimer: For the best experience, read this article in its original MD format, that includes embedded code snippets…

  • Mastering `Optional` in Java: Eliminate Nulls Enhancing Code Readability

    Mastering `Optional` in Java: Eliminate Nulls Enhancing Code Readability

    Disclaimer: For the best experience, read this article in its original MD format, that includes embedded code snippets…

  • Functional Interfaces in Java

    Functional Interfaces in Java

    Disclaimer: For the best experience, read this article in its original MD format, that includes embedded code snippets…

  • Functions as First-class citizens in Java

    Functions as First-class citizens in Java

    Disclaimer: For the best experience, read this article in its original MD format, that includes embedded code snippets…

  • Data Immutability in Java

    Data Immutability in Java

    Disclaimer: For the best experience, read this article in its original MD format, that includes embedded code snippets,…

  • Functional Programming in Java

    Functional Programming in Java

    Functional Programming is a programming paradigm that decomposes a problem into a set of Functions, focusing on…

  • Introduction to Functional Programming

    Introduction to Functional Programming

    What is Functional Programming In Computer Science, Functional Programming is a programming paradigm that decomposes a…

  • Menos es Más. Aumentar la productividad del sistema reduciendo

    Menos es Más. Aumentar la productividad del sistema reduciendo

    Un proceso es una secuencia de actividades coordinadas para alcanzar un objetivo específico. Cada paso de nuestro…

    1 条评论
  • Test-Driven Development (TDD) for Effective Planning

    Test-Driven Development (TDD) for Effective Planning

    Prioritization is the most impactful activity to determine long-term success in software development. There are a…

    1 条评论
  • Quick and Easy Introduction to Test-Driven Development (TDD)

    Quick and Easy Introduction to Test-Driven Development (TDD)

    Test-Driven Development (TDD) is a software development approach that follows a simple yet powerful iterative cycle:…

社区洞察

其他会员也浏览了