Function functional interface

In this post, with an example I will show how to use Function functional interface.

Function interface is a functional interface that takes an input and produces an output. This is achieved by its “apply” method.

Below is an example

Main Code


1  package function;
2  
3  import java.util.ArrayList;
4  import java.util.List;
5  import java.util.function.Function;
6  
7  public class FunctionDemo1 {
8   public static void main(String[] args) {
9       List<String> list = new ArrayList<String>();
10      list.add("0");
11      list.add("1");
12      list.add("2");
13      list.add("3");
14      list.add("4");
15      list.add("5");
16      list.add("6");
17      list.add("7");
18      list.add("8");
19      list.add("9");
20      
21      CustomFunction customFunction = new CustomFunction();
22      
23      for(String data : list) {
24          Integer value = customFunction.apply(data);
25          System.out.println(value);
26      }
27  }
28 }
29 
30 class CustomFunction implements Function<String, Integer> {
31  @Override
32  public Integer apply(String data) {
33      Integer value = Integer.parseInt(data);
34      return value;
35  }
36 }

The above code takes a list of String values and convert each one to Integer and print the value to the console.

The conversion of String to Integer is given to CustomFunction class which is an implementation of Function Interface.

The logic to convert String to Integer is added in the apply method of CustomFunction class. Refer to line 32 to 34.

The apply method takes an input (which in this case is String value) and produces an output (which in this case is an Integer value).

At line 21, we create an instance of CustomFunction class.

In the loop at line 23, we continuously pass the String data available in the list to CustomFunction’s apply method and print the return value of apply method.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s