Using Lambda Expressions With Functional Interfaces in Java

by JPK14 in Circuits > Software

505 Views, 0 Favorites, 0 Comments

Using Lambda Expressions With Functional Interfaces in Java

intro.JPG

Functional Interfaces in Java are a very useful tool that many newer programmers don't utilize. They allow developers to abstract their code so that it can be applied to many different problems. This is especially useful with Lambda expressions which allow functions to be created within a method's parameters. These instructions show how to use a very basic Functional interface called Function. Function has an abstract method called apply that takes one parameter of generic type and returns a generic type. Apply does not have to be defined until the call of the method that calls apply. This is very powerful because it allows programmers to use the same piece of code multiple times only having to change the call to that method.

Create a Java Project

Open an IDE and create a java project, the name is not important. I have named mine "Instructions."

Create a Package

2. package.JPG

Create a new package in the source file, named “instructions.”

Create the Converter Class

In the instructions package, create a new class called Converter and Import java.util.function.Function.

Create the FunctionTest Class

5. Classes.JPG

In the instructions package, create a new class called FunctionTest.

Create the Convert Method

6. convert.JPG

In the Converter class, Create a method called "convert" that returns a String s and takes in an int x and a Function f as parameters.

Add Type Parameters

Add type parameters Integer and String to the Function f parameter.
This should look like: Function f

Calling Apply

8. apply.JPG

Return the result of calling the apply function on f with x and a parameter by return f.apply(x)

Main Method

Create a main method in FunctionTest.

Start to Call Convert

In the main method of the FunctionTest class start to call the convert method Converter.convert(

Choose an Integer

11. convert int.JPG

Inside the parentheses, enter an int that you would like to convert to a string. This should look like the picture above.

Seperate the Parameters

The next parameter is the Lambda function. With the cursor at the position in the image above, type a comma then a space to delineate between the two parameters.

Lambda Function Parameter

Next, you will type the parameters for the lambda function. (Integer x) is our only parameter

Lambda Function Body

14. Lambda.JPG

Following the parameter, type -> to signal that the next text is the body of the function. Type x.toString, close the parentheses, and finish with a semicolon.

Assign Result

To make sure the program is working, assign the call to convert to a String variable called result

Test

16. result.JPG

Check that result is equal to the string version of the Integer parameter that you chose. One simple way to do this is with an if statement, shown below.