Functional programming is a style of programming where you build programs using functions. It focuses on using pure functions (functions without side effects) and avoiding shared state and mutable data. This makes the code more predictable and easier to test.
Key Concepts:
A pure function does not modify any external state and returns the same result for the same input.
public class PureFunctionDemo {
public static void main(String[] args) {
System.out.println(add(2, 3)); // Output: 5
System.out.println(add(2, 3)); // Output: 5 (same input, same output)
}
public static int add(int a, int b) {
return a + b;
}
}
Immutable data cannot be changed once created. Instead, new data is created.
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
public class ImmutabilityDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Create a new list with each element doubled
List<Integer> doubledNumbers = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
System.out.println("Original List: " + numbers); // Output: [1, 2, 3, 4, 5]
System.out.println("Doubled List: " + doubledNumbers); // Output: [2, 4, 6, 8, 10]
}
}
Higher-order functions take other functions as arguments or return functions as results.
Example: Using a Higher-Order Function
import java.util.function.Function;
public class HigherOrderFunctionDemo {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x;
System.out.println(applyFunction(square, 5)); // Output: 25
}
public static int applyFunction(Function<Integer, Integer> func, int value) {
return func.apply(value);
}
}