Functional programming (FP) in Java leverages features introduced in Java 8 and later, such as lambdas, streams, and functional interfaces, to enable a declarative, immutable, and side-effect-free coding style. Below is a concise overview of key FP concepts and how they are implemented in Java:
1. Pure Functions
- Concept: Functions that always produce the same output for the same input and have no side effects (e.g., no mutation of external state).
// Pure function: No side effects, deterministic
int square(int x) {
return x * x;
}
//Avoid modifying external variables or state within methods.
Code language: JavaScript (javascript)
2. Immutability
- Data cannot be changed once created, reducing side effects and making code thread-safe.
- Java Implementation:
- Use final for variables and immutable classes (e.g., String, Integer).
- Leverage records (Java 14+)
Â
record Point(int x, int y) {} // Immutable by default
Code language: JavaScript (javascript)
- Â Â Use immutable collections
List<Integer> immutableList = List.of(1, 2, 3); // Unmodifiable
Code language: PHP (php)
3. First-Class and Higher-Order Functions
- Concept: Functions are treated as first-class citizens (can be passed as arguments, returned, or assigned to variables) and higher-order functions take or return other functions.
- Java Implementation:
- Use lambda expressions and functional interfaces (e.g., Function, Predicate):
Â
- Use lambda expressions and functional interfaces (e.g., Function, Predicate):
import java.util.function.Function;
Function<Integer, Integer> square = x -> x * x;
Function<Integer, Integer> doubleIt = x -> x * 2;
// Higher-order function: Applying function as an argument
int result = square.apply(5); // 25
Code language: PHP (php)
4. Function Composition
- Concept: Combining multiple functions to create a new function.
- Java Implementation:
- Use Function.compose or Function.andThen:
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> square = x -> x * x;
// (x + 1)^2
Function<Integer, Integer> addOneThenSquare = square.compose(addOne);
System.out.println(addOneThenSquare.apply(3)); // (3+1)^2 = 16
Code language: PHP (php)
5. Lambdas and Anonymous Functions
- Concept: Concise syntax for defining functions inline.
- Java Implementation:
// Lambda expression as a Comparator
List<String> names = Arrays.asList("Bob", "Alice", "Charlie");
names.sort((a, b) -> a.compareTo(b)); // Sorts alphabetically
Code language: JavaScript (javascript)
6. Streams and Lazy Evaluation
- Concept: Process collections declaratively with operations that are evaluated only when needed (lazy evaluation).
- Java Implementation:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenSquares = numbers.stream()
.filter(n -> n % 2 == 0) // Lazy
.map(n -> n * n) // Lazy
.collect(Collectors.toList()); // Eager
// Output: [4, 16]
Code language: PHP (php)
7. Monads(Optional and Stream)
- Concept: Structures that encapsulate computations, enabling chaining operations while handling side cases (e.g., nulls, errors).
- Java Implementation:
- Use Optional to handle potential null values:
Â
- Use Optional to handle potential null values:
Optional<String> name = Optional.of("Mahesh");
String upperName = name.map(String::toUpperCase).orElse("UNKNOWN");
// Output: MAHESH
Code language: JavaScript (javascript)
8. Functional Interfaces
- Concept: Interfaces with a single abstract method, used as the basis for lambda expressions.
- Java Implementation:
- Built-in interfaces: Function<T, R>, Predicate<T>, Consumer<T>, Supplier<T>.
- Custom functional interface:
Â
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
MathOperation addition = (a, b) -> a + b;
System.out.println(addition.operate(2, 3)); // 5
Code language: PHP (php)
Program
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class FunctionalExample { public static void main(String[] args) { List<String> names = Arrays.asList("Paani", "Raj", "Mahesh"); List<String> result = names.stream() .filter(name -> name.length() > 3) .map(String::toUpperCase) .sorted() .collect(Collectors.toList()); System.out.println(result); // [MAHESH, PAANI] } }
Java supports functional programming through lambdas, streams, and functional interfaces, enabling a declarative and immutable style. While not a purely functional language, Java’s FP features allow developers to write cleaner, more modular code.