Code

Lambda Expressions and Functional Interfaces in Java

Lambda Expressions and Functional Interfaces in Java

Python Basics: A Free Course for All Skill Levels Portfolio Creation: 4 Engaging Projects and Interactive Learning Explore the Course: What to Expect During the Course

Learn More

Let's create functions that will calculate the sum and product of two numbers:

Now let's create a single method, call it processTwoNumbers. This method will take two numeric parameters and code to process them.

private int processTwoNumbers(int a, int b, [code goes here])

When using the sum method, the third parameter will take the operation a+b as an argument, while for the mult method, this parameter will take the value a*b.

It is worth noting that the third argument can only be code that takes two parameters of a certain type (in our case, int) and produces a result of the desired type - int.

We should somehow notify the compiler that it is necessary to prevent future programmers from passing incorrect code (for example, a+b+c).

In this case, we need a method signature, which will act as the third parameter for our processTwoNumbers method.

private int computeSumOfTwoIntegers(int a, int b, [method signature])

How can we add a third parameter without making the processTwoNumbers method signature too cumbersome and difficult to read? The developers of Java found an elegant solution to this problem. They developed the concept of functional interfaces.

Definition of a Functional Interface: Key Aspects

A functional interface is an interface that includes only one abstract method, which is a description of the method without its implementation. In this case, static methods and methods with a default implementation are not taken into account, and their number in the functional interface is unlimited.

If a method takes a functional interface as a parameter, then when calling it, you must pass a code block as one of the arguments.

The provided code fragment must meet the following requirement: its signature must be identical to the signature of the only abstract method of the functional interface.

To clarify the situation, let's look at a specific example:

Java has a number of predefined functional interfaces that differ in both the number and type of input and output parameters. An example of such an interface is ToIntBiFunction, which was mentioned earlier. When developing your own functional interface, it's crucial to remember to add the @FunctionalInterface annotation. This annotation ensures that the compiler can verify that the interface you're creating actually meets the criteria for a functional interface.

The functional interface ToIntBiFunction perfectly matches the example we started with. This means we can use it as an argument, passing code that:

  • The function takes two arguments (T t, U u), where T and U indicate the ability to use parameters of different types. For example, these could be Long and String. However, in our case, this is unnecessary, since both arguments have the same type - int.
  • returns the result as an integer.

Here's what you get:

The ToIntBiFunction interface implies that you must provide a method that will have the same signature as the method defined within this interface.

In order to implement the passed code within the processTwoNumbers method, you must call the method from the functional interface.

Now we come to the topic of lambda expressions.

Understanding Lambda Expressions: Basic Concepts

It's a succinct notation, inspired by the lambda calculus, designed to pass pieces of code as arguments to another program.

Basically, it's a class or method without a name. Since everything in Java except for primitive types is an object, lambda expressions must also be associated with a specific object type. This type, as you might have guessed, is called a functional interface.

Thus, the lambda expression is not an independent element, but serves to implement a method defined in the functional interface.

If there were no lambdas, each time we called the processTwoNumbers method, we would require the following approach:

It is important to note that in the given example, biFunction is implemented using anonymous classes. Otherwise, we would have to create a separate class that implements the ToIntBiFunction interface and includes the applyAsInt method. By using an anonymous class, we were able to accomplish this task quickly and efficiently without creating additional classes.

In the given example, all but one line of code is redundant. Only the return a + b expression carries the functional load, while the rest of the code is technical excess. Their number turned out to be quite significant, even for a simple implementation of the operation of adding two numbers.

This is where lambda expressions come to the rescue. Thanks to them, the process of creating a biFunction is significantly simplified and can be done in just ten characters!

A lambda expression has the following structure: (arguments) -> (function body)

Our lambda will look like this:

A bi-function that takes two integers and returns their sum can be defined as follows: ToIntBiFunction biFunction = (a, b) -> a + b;

And so, this set of 10 characters can be used as an argument for a method that takes a functional interface as a parameter. In this case, as a rule, they do without creating an intermediate variable and pass the lambda directly.

The compiler will ensure that the lambda expression conforms to the functional interface requirements, meaning it accepts the required number of arguments of the required types. In this case, we are using the ToIntBiFunction functional interface. Its only abstract method has a signature that specifies two parameters: (Integer a, Integer b).

For example, if you call the method this way, the code will fail to compile, since only one argument will be used:

There are many ways to write lambdas. We have studied only one of them.

Using lambda expressions in various areas.

In various situations. One common example is iterating over elements using a loop:

Lambdas are also used in comparators when implementing sorting. Let's consider a situation where we need to order a collection based on the last letter of each word:

In most cases, when using collections in combination with the Stream API, it is difficult to do without lambda expressions. In the following example, we first filter the data stream based on a specific value (using the filter method), then transform each element (the map method), and finally collect the results into a list (the collect method):