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 and references to code examples.

Functional Programming emphasizes the use of immutable data and pure functions to achieve more predictable, maintainable, and thread-safe code.

While Java is not inherently a functional language, Java 8 (2014) introduced some major features to support these concepts. We have already seen how Data Immutability can be achieved in Java.

Let's review in this article how Functions became First-class citizens.

Functions as Variables

Since Java 8, Functions can be assigned to variables and used like any other variable.

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> squareFunction = x -> x * x;
        Function<Integer, Integer> doubleFunction = x -> x * 2;

        System.out.println(squareFunction.apply(5)); // Output: 25
        System.out.println(doubleFunction.apply(5)); // Output: 10
    }
}        

Passing Functions as Arguments

Since Java 8, Functions can be passed as arguments, making high-order programming possible which is a key concept in Functional Programming.

Here's an example using the `Function` interface to pass a function as an argument:

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> squareFunction = x -> x * x;

        System.out.println(applyFunction(5, squareFunction)); // Output: 25
    }
    
    public static int applyFunction(int value, Function<Integer, Integer> function) {
        return function.apply(value);
    }
}        

Returning Functions from Functions

Another key concept became possible fron Java 8, Functions can also return Functions.

Here's an example of a function that returns another function:

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> squareFunction = createFunction("square");
        System.out.println(squareFunction.apply(5)); // Output: 25

        Function<Integer, Integer> doubleFunction = createFunction("double");
        System.out.println(doubleFunction.apply(5)); // Output: 10
    }
    
    public static Function<Integer, Integer> createFunction(String type) {
        if ("square".equals(type)) {
            return x -> x * x;
        } else if ("double".equals(type)) {
            return x -> x * 2;
        }
        return x -> x;
    }
}        

Composing Functions

Function composition allows combining smaller functions into larger operations, making the code more modular, reusable and easier to test.

  • `Function.andThen`: Applies the first function, then the second.
  • `Function.compose`: Applies the second function, then the first.

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> squareFunction = x -> x * x;
        Function<Integer, Integer> doubleFunction = x -> x * 2;

        Function<Integer, Integer> squareThenDouble = squareFunction.andThen(doubleFunction);
        System.out.println(squareThenDouble.apply(5)); // Output: (5 ^ 2) * 2 = 50

        Function<Integer, Integer> addThenMultiply = squareFunction.compose(doubleFunction);
        System.out.println(addThenMultiply.apply(5)); // Output: (5 * 2) ^ 2 = 100
    }
}        

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

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…

  • 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…

  • 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:…

社区洞察

其他会员也浏览了