Functional Programming

Lambda

In Java, lambdas are defined as below:

(parameters) -> expression;

Brackets for parameters are optional if there is only one parameter and its type is inferred.

List<String> list = Arrays.asList("a", "b", "c");
list.forEach(item -> System.out.println(item));

Functional Interfaces

Interfaces in Java which have only one abstract method.

In other (natively functional) languages like JavaScript, you can assign functions to variables. This was not possible in Java.

If an interface however had only one abstract method, and we assign a function to a reference of that interface, the language can automatically assign the function to the abstract method - thereby supporting assigning and passing the functions.

Useful functional interfaces

Function

  • Represents a function that takes one argument and produces one result.
  • Used for expressing computations and transformations.
Definition
@FunctionalInterface
public interface Function<T, R> {
	R apply(T t);
}

T - input type R - output type

Usage
Function<String, Integer> stringLength = s -> s.length();
int lengthOfHello = stringLength.apply("Hello"); // 5

BinaryOperator

  • Extends #`Function`.
  • Takes two inputs and returns one - all of the same type.
  • Great for performing binary operations on objects like 2+5=7
Definition
@FunctionalInterface
public interface BinaryOperator<T> {
	T apply(T t, T u);
}
Usage
BinaryOperator<Integer> sum = (x, y) -> x + y;
int result = sum.apply(5, 3); // 8

Predicate

  • Extends #`Function`.
  • represents a boolean-values function that takes one argument.
  • Provides a convenient way to define and pass around functions that return a true or false value based on their input.
Definition
@FunctionalInterface
public interface Predicate<T> {
	boolean test(T t);
}

It is also generic.

Usage
Predicate<String> isEvenLength = s -> s.length() % 2 == 0;
boolean result = isEvenLength.test("Hello");

Consumer

Represents an action that takes in a single input and returns no result.

Definition
@FunctionalInterface
public interface Consumer<T> {
	void accept(T t);
}

Useful Methods

andThen()

andThen is a method present in functional interfaces such as #`Function`, #`Predicate` and #`Consumer` to allow you to chain the operations together.

You can pass it a second operation which is supposed to follow the first.

Definition
R andThen(Function<? super T, ? extends R> after) //R is a functional interface
Usage
Function<String, Integer> stringLength = s -> s.length();
Function<Integer, String> intToString = i -> String.valueOf(i);
Function<String, String> lengthToString = stringLength.andThen(intToString);
String result = lengthToString.apply("Hello"); // "5"

References

© 2025 All rights reservedBuilt with Flowershow Cloud

Built with LogoFlowershow Cloud