top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Functional Programming in Java

Introduction

Functional programming in Java deals with using pure functions, immutability, and higher-order functions. It is an important concept in Java, and here is a tutorial for learners to master it quickly.

Overview

This tutorial deals with basic concepts such as functional programming in Java: how functional techniques improve your Java programs, the differences between functional and purely functional programming, why functional programming matters, and much more. 

What Is Functional Programming?

Functional programming in Java is a programming paradigm that emphasizes using higher-order functions, immutability, and pure functions. It introduces features like lambda expressions and the Stream API to support functional-style programming. This approach promotes code readability, modularity, and reusability while enabling better parallel and concurrent programming.

Functional Programming Vs. Purely Functional Programming

How to Implement Functional Programming in Java?

In Java, functional programming can be implemented using features introduced in Java 8 and subsequent versions. Here's how you can implement functional programming in Java:

  • Lambda Expressions: Lambda expressions allow you to define and use anonymous functions in Java. They provide a concise syntax for implementing functional interfaces.

Syntax: (parameter list) -> { function body }

  • Functional Interfaces: Functional interfaces are interfaces that have exactly one abstract method. They serve as the basis for lambda expressions and method references.

Syntax: @FunctionalInterface
interface MyFunctionalInterface {
    void performAction();
}

  • Stream API: The Stream API provides a set of operations for processing data collections in a functional and declarative style.

Syntax: stream()
    .filter(predicate)
    .map(mapper)
    .reduce(identity, accumulator)

Concepts of Functional Programming

Now, let us explore some of the core concepts of functional programming.

Higher-order functioning

In Java, higher-order functions can be implemented using functional interfaces. A higher-order function takes one or more functions as arguments and/or returns a function. 

Example:

In this example, we have two functions: square and increment. The square function squares a given number, and the increment function increments a given number by 1.

The compose function is a higher-order function that takes two functions as arguments and returns a new function. In this case, we use the compose() method provided by the Function functional interface to compose the square and increment functions.

The composed function first applies the increment function to the input and then the square function to the result. This means that the square function is applied to the result of the increment function.

In the main() method, we create the square and increment functions using lambda expressions. Then, we compose these functions using the compose() method to create the compose function. Finally, we apply the compose function to the number 5 using the apply() method, resulting in 36.

import java.util.function.Function;
public class main {
    public static void main(String[] args) {
        Function<Integer, Integer> square = num -> num * num;
        Function<Integer, Integer> increment = num -> num + 1;
        Function<Integer, Integer> compose = square.compose(increment);
        int result = compose.apply(5); // Output: 36
        System.out.println("Result: " + result);
    }
}

Pure Functions

A pure function is a function that always produces the same output for the same input and has no side effects. It does not modify any external state or rely on mutable data.

Example:

In this example, the multiply() function is pure. It takes two integers as input, multiplies them, and returns the result.

When we call the multiply() function with the same input values (5 and 3), it will always return the same output (15). The function has no side effects, such as modifying global variables or printing to the console.

public class PureFunctionExample {
    public static int multiply(int a, int b) {
        return a * b;
    }
    public static void main(String[] args) {
        int result = multiply(5, 3); // Output: 15
        System.out.println("Result: " + result);
    }
}

Lambda Expressions

Lambda expressions in Java allow you to define and use anonymous functions concisely.

Example:

In this example, we first import the necessary classes (ArrayList, List, Consumer) and define a class called main. Then, in the main() method, we create an ArrayList called names and add some strings. We use the forEach() method on the names list to iterate over each element.

We can then define a functional interface called Calculator with a single abstract method calculate(). A lambda expression (a, b) -> a + b implements the calculate() method, adding two integers and returning the sum. We then create an instance of the Calculator functional interface using the lambda expression and calculate the sum of 5 and 3.

A Consumer functional interface is then defined with a single abstract method accept().

The lambda expression str -> System.out.println(str.toUpperCase()) implements the accept() method, printing the uppercase version of the given string.

We create an instance of the Consumer functional interface using the lambda expression and call the accept() method with the string "hello", which prints "HELLO" to the console. Finally, we define the Calculator functional interface with a single abstract method calculate() that takes two integers and returns an integer.

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("John");
        names.add("Jane");
        names.add("Alice");
        // Example 1: Using a lambda expression as a parameter
        names.forEach(name -> System.out.println("Hello, " + name));
        // Example 2: Using a lambda expression with multiple parameters
        Calculator add = (a, b) -> a + b;
        int sum = add.calculate(5, 3);
        System.out.println("Sum: " + sum);
        // Example 3: Using a lambda expression as a variable
        Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase());
        printUpperCase.accept("hello");
    }
    interface Calculator {
        int calculate(int a, int b);
    }
}

Imperative Programming Paradigm

Imperative programming is a programming paradigm where programs are structured around the concept of state and instructions that change that state. In imperative programming, you explicitly specify the sequence of steps to be executed to achieve a desired result.

Example:

public class ImperativeProgrammingExample {
    public static void main(String[] args) {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] % 2 == 0) {
                sum += numbers[i];
            }
        }
        System.out.println("Sum of even numbers: " + sum);
    }
}

Declarative Programming Paradigm

Declarative programming is a programming paradigm where programs describe the desired results or outcomes without specifying the step-by-step procedure to achieve those results. In declarative programming, you focus on what you want to accomplish rather than how.

Example:

import java.util.Arrays;
public class DeclarativeProgrammingExample {
    public static void main(String[] args) {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int sum = Arrays.stream(numbers)
                        .filter(n -> n % 2 == 0)
                        .sum();
        System.out.println("Sum of even numbers: " + sum);
    }
}

Functional Programming Techniques

Here are some functional programming techniques:

Function

In Java, a function is represented by a method. A method is a block of code that performs a specific task and can be invoked or called from other parts of the program.

Example:

public class main {
    public static void main(String[] args) {
        // Calling the function
        int sum = addNumbers(5, 3);
        System.out.println("Sum: " + sum);
    }
    // Function to add two numbers and return the result
    public static int addNumbers(int a, int b) {
        int sum = a + b;
        return sum;
    }
}

Function Composition

Function composition is a technique in functional programming where you combine multiple functions to create a new function. The output of one function becomes the input for the next function, forming a chain of operations.

Example:

import java.util.function.Function;
public class main {
    public static void main(String[] args) {
        // Define two functions: addOne and multiplyByTwo
        Function<Integer, Integer> addOne = x -> x + 1;
        Function<Integer, Integer> multiplyByTwo = x -> x * 2;
        // Compose the functions
        Function<Integer, Integer> composedFunction = addOne.andThen(multiplyByTwo);
        // Apply the composed function to an input
        int result = composedFunction.apply(5);
        System.out.println("Result: " + result); // Output: 12
    }
}

Monads

Monads are a programming concept commonly used in functional programming to manage and encapsulate computations with additional context. While Java doesn't have built-in support for monads, we can still implement monad-like behavior using libraries like Vavr or custom code.

First, we must the Vavr dependency to your project. We can use a build tool like Maven for managing dependencies. In the case of Maven, we must add the following dependency to our pom.xml file:

We can then import the necessary Vavr classes in our code in this manner:

Finally, we can run the below code with the Vavr library:

Currying

Currying is a technique in functional programming where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument.

Example:

import java.util.function.Function;
public class main {
    public static void main(String[] args) {
        // Currying a two-argument function
        Function<Integer, Function<Integer, Integer>> curriedAdd = a -> b -> a + b;
        // Partially apply the first argument
        Function<Integer, Integer> add5 = curriedAdd.apply(5);
        // Call the curried function with the remaining argument
        int result = add5.apply(3);
        System.out.println("Result: " + result); // Output: 8
    }
}

Recursion

Recursion in Java is a programming technique where a method can call itself for solving problems by breaking them down into similar but smaller subproblems. In a recursive function, the function repeatedly calls itself with modified inputs until a base case is reached, which defines the terminating condition for the recursion.

Example:

public class main {
    public static void main(String[] args) {
        int number = 5;
        int factorial = calculateFactorial(number);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
    public static int calculateFactorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * calculateFactorial(n - 1);
        }
    }
}

Advantages of Functional Programming 

There are many advantages of Functional Programming. Some of them are:

  • Bugs-Free Code: Functional programming languages promote immutability and avoid mutable states. This reduces the chances of bugs caused by unexpected side effects. 

  • Efficient Programming Language: With no mutable state, functional programming allows for parallel execution of functions, improving efficiency and performance. The independent units in functional programs can run concurrently, leading to better utilization of system resources.

  • Supports Nested Functions: Functional programming languages support nested functions. This allows functions to be defined within other functions. This promotes modularity and encapsulation. Further, enabling the creation of more reusable and expressive code.

  • Lazy Evaluation: Functional programming languages often support lazy evaluation. This means that expressions are not evaluated until their results are needed. This can lead to more efficient use of resources. This is because the required computations are performed when needed.

Differences Between Functional Programming and Object-Oriented Programming

Conclusion

This tutorial will be beneficial for students keen on mastering functional programming in Java. Since it is one of the most important concepts of Java, one must carefully go through tutorials and learning materials to grasp such concepts. One could also enroll in online learning platforms such as upGrad to learn more about these concepts from industry experts with the help of specially tailored courses. 

FAQs

1. What are lambda expressions in functional programming?

Lambda expressions are anonymous functions that allow you to define functionality inline concisely. They are a key feature of functional programming in Java.

2. Is functional programming suitable for all types of Java projects?

Functional programming can be beneficial in various Java projects, especially those that involve processing collections, parallel execution, or complex data transformations. 

3. Are there any frameworks or libraries that support functional programming in Java?

Yes, several libraries and frameworks in the Java ecosystem support functional programming. Some popular ones include Google Guava and Java 8's Stream API itself. These libraries provide additional functional programming features and utilities to enhance your Java code.

Leave a Reply

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