Java
Programming
Function Passing
Parameters
Code Optimization

How to pass a function as a parameter in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Passing functions as parameters in Java programs is a concept closely tied to the utilization of functional interfaces and lambda expressions, which were introduced in Java 8. This approach is commonly used in functional programming paradigms to create more modular, flexible, and reusable code.

Understanding Functional Interfaces and Lambda Expressions

A functional interface in Java is any interface that contains exactly one abstract method. This restriction makes it a candidate for lambda expressions, which provide a concise way to instantiate interfaces using an expression. The most commonly used functional interface in Java is java.util.function.Function, but there are many others like Consumer, Supplier, and Predicate.

Here is how functional interfaces and lambda expressions are typically used:

java
1@FunctionalInterface
2interface MathOperation {
3    int operation(int a, int b);
4}
5
6public class Main {
7    public static void main(String[] args) {
8        MathOperation addition = (a, b) -> a + b;
9        int result = executeOperation(5, 3, addition);
10        System.out.println("5 + 3 = " + result);
11    }
12
13    private static int executeOperation(int a, int b, MathOperation mathOp) {
14        return mathOp.operation(a, b);
15    }
16}

In the code above, MathOperation is a functional interface with a single method operation. We pass a lambda expression (a, b) -> a + b that implements this method when we call executeOperation.

Practical Examples of Using Functions as Parameters

  1. Using Predicates:
    Predicates are functional interfaces in Java used to return a boolean value based on the input. They are often used for filtering data.
java
1   import java.util.ArrayList;
2   import java.util.function.Predicate;
3
4   public class Main {
5       public static void main(String[] args) {
6           ArrayList<Integer> numbers = new ArrayList<>();
7           numbers.add(10);
8           numbers.add(23);
9           numbers.add(36);
10           numbers.add(45);
11           
12           numbers.removeIf(n -> n % 2 == 0);  // Remove even numbers
13           numbers.forEach(System.out::println);  // Print remaining numbers
14       }
15   }
  1. Java Stream API:
    Stream API extensively uses lambda expressions. Functions as parameters facilitate operations such as mapping, filtering, and reduction on streams of elements.
java
1   import java.util.Arrays;
2   import java.util.List;
3   import java.util.stream.Collectors;
4
5   public class Main {
6       public static void main(String[] args) {
7           List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
8           List<Integer> squaredNumbers = numbers.stream()
9              .map(n -> n * n)
10              .collect(Collectors.toList());
11
12           squaredNumbers.forEach(System.out::println);
13       }
14   }

Advantages of Using Functions as Parameters

AdvantageDescription
Code ReusabilityFunctions can be passed around and reused in different contexts.
ModularityHelps in breaking down the code into smaller, manageable pieces.
Higher-level AbstractionsFacilitates operations on a higher abstraction level, like stream operations.
DecouplingFunctions as parameters promote looser coupling between components of the software.

Conclusion

Passing functions as parameters in Java enables a flexible, functional programming style that can significantly enhance the modularity and reusability of the code. It allows developers to write concise and expressive code, particularly with the use of lambda expressions and functional interfaces, which is powerful in domains such as concurrent programming, event handling, and collection manipulation.

Understanding and applying these concepts effectively can lead to cleaner, more efficient Java code and pave the way for adopting more advanced functional programming techniques.


Course illustration
Course illustration

All Rights Reserved.