In this article, we will discuss highly used pre-defined Functional Interface in Java 1.8 version for performing operation based on input argument and returning results after computation/processing i.e.; Function Functional Interface
1. Function Functional Interface:
- This Functional Interface has one abstract method called R apply(T t); which
- Step 1 :- accepts 1 input argument of any data-type
- Step 2 :- performs some operation on the input argument
- Step 3 :- And returns result of any data-type
- Below is interface Function containing apply(); method along with other default & static methods
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
// other default and static methods
}
Examples for Function Functional Interface:
Example 1 – program to find out square of a given integer number
package net.bench.resources.function.example;
import java.util.function.Function;
public class SquareOfNumber {
public static void main(String[] args) {
// lambda expression to find square of number
Function<Integer, Integer> f = i -> i*i;
// computing Square of an Integer using Function FI
System.out.println("1. The Square of number 5 is \t: " + f.apply(5));
System.out.println("2. The Square of number 9 is \t: " + f.apply(9));
System.out.println("3. The Square of number 27 is \t: " + f.apply(27));
System.out.println("4. The Square of number 33 is \t: " + f.apply(33));
System.out.println("5. The Square of number 43 is \t: " + f.apply(43));
}
}
Output:
1. The Square of number 5 is : 25
2. The Square of number 9 is : 81
3. The Square of number 27 is : 729
4. The Square of number 33 is : 1089
5. The Square of number 43 is : 1849
Example 2 – program to find length of given String
package net.bench.resources.function.example;
import java.util.function.Function;
public class FindLengthOfString {
public static void main(String[] args) {
// lambda expression to find length of String
Function<String, Integer> f = s -> s.length();
// computing length of String using Function FI
System.out.println("1. Length of String 'BenchResources' is : "
+ f.apply("BenchResources"));
System.out.println("2. Length of String 'Java 8' is \t: "
+ f.apply("Java 8"));
System.out.println("3. Length of String 'Anushka' is \t: "
+ f.apply("Anushka"));
System.out.println("4. Length of String 'Tendulkar' is \t: "
+ f.apply("Tendulkar"));
System.out.println("5. Length of String 'Madhavan' is \t: "
+ f.apply("Madhavan"));
}
}
Output:
1. Length of String 'BenchResources' is : 14
2. Length of String 'Java 8' is : 6
3. Length of String 'Anushka' is : 7
4. Length of String 'Tendulkar' is : 9
5. Length of String 'Madhavan' is : 8
Example 3 – program to return Uppercase & Lowercase for given Strings
package net.bench.resources.function.example;
import java.util.function.Function;
public class CaseConversionForString {
public static void main(String[] args) {
// 1 - lambda expression to return UpperCase String
Function<String, String> f1 = s -> s.toUpperCase();
// 2 - lambda expression to return LowerCase String
Function<String, String> f2 = s -> s.toLowerCase();
System.out.println("Upper Case conversion\n=========================");
// converting String to UpperCase using Function FI
System.out.println("1. UpperCase of String 'america' is \t: "
+ f1.apply("america"));
System.out.println("2. UpperCase of String 'russia' is \t: "
+ f1.apply("russia"));
System.out.println("3. UpperCase of String 'china' is \t: "
+ f1.apply("china"));
System.out.println("\n\nLower Case conversion\n=========================");
// converting String to LowerCase using Function FI
System.out.println("1. LowerCase of String 'INDIA' is \t: "
+ f2.apply("INDIA"));
System.out.println("2. LowerCase of String 'ICELAND' is \t: "
+ f2.apply("ICELAND"));
System.out.println("3. LowerCase of String 'IRELAND' is \t: "
+ f2.apply("IRELAND"));
}
}
Output:
Upper Case conversion
=========================
1. UpperCase of String 'america' is : AMERICA
2. UpperCase of String 'russia' is : RUSSIA
3. UpperCase of String 'china' is : CHINA
Lower Case conversion
=========================
1. LowerCase of String 'INDIA' is : india
2. LowerCase of String 'ICELAND' is : iceland
3. LowerCase of String 'IRELAND' is : ireland
Example 4 – program to find grade of Students
package net.bench.resources.function.example;
import java.util.function.Function;
class Student {
// member variables
String name;
int marks;
// public constructor
public Student(String name, int marks) {
super();
this.name = name;
this.marks = marks;
}
}
public class StudentResultCalculation {
public static void main(String[] args) {
// lambda expression to find grade of Student supplied
Function<Student, String> f = student -> {
// alternatively, we can switch statement as well
if(student.marks >= 90)
return "Merit";
else if(student.marks >= 75)
return "Distinction";
else if(student.marks >= 60)
return "First class";
else if(student.marks >= 50)
return "Second class";
else if(student.marks >= 35)
return "Pass class";
else
return "Failed";
};
// create Student object for applying Function
Student[] sArray = {
new Student("Vijay", 97),
new Student("Ajith", 78),
new Student("Vikram", 66),
new Student("Surya", 54),
new Student("Karthi", 43),
new Student("Arya", 31)
};
// iterate and find Student grade using Function FI
System.out.println("Name\tMarks\tGrade\n");
for(Student s : sArray) {
System.out.println(s.name + "\t" + s.marks + "\t" + f.apply(s));
}
}
}
Output:
Name Marks Grade
Vijay 97 Merit
Ajith 78 Distinction
Vikram 66 First class
Surya 54 Second class
Karthi 43 Pass class
Arya 31 Failed
2. Function Joining :
- When we want to combine 2 or more Function Functional Interface into one, then it is called as Function Joining
- We can do 2 types Function joining i.e.; andThen(); & compose();
- Assume that 1st Function calculates square of a Integer number and 2nd Function doubles the squared number
- Using “andThen” Function, 1st Function calculates square and then applies 2nd Function to double the squared number
- Using “compose” Function, first 2nd Function double the given Integer number and then applies 1st Function to square the doubled number
- compose Function :- it is just reverse of “andThen” Function
- We will look at example for each case separately
Example 1 – andThen Function
- First, 1st Function Computed i.e.; given Integer is doubled and then
- 2nd Function is computed i.e.; doubled number is squared and
- Final result is returned i.e.; final squared result is printed into console
package net.bench.resources.function.example;
import java.util.function.Function;
public class AndThenFunction {
public static void main(String[] args) {
// 1 - lambda expression to double the given Integer using Function FI
Function<Integer, Integer> f1 = i -> 2*i;
// 2 - lambda expression to square the given Integer using Function FI
Function<Integer, Integer> f2 = i -> i*i;
// evaluating given Integer using Function joining
System.out.println("1. Double the number 5 and then square it \t: "
+ f1.andThen(f2).apply(5));
System.out.println("2. Double the number 19 and then square it \t: "
+ f1.andThen(f2).apply(19));
System.out.println("3. Double the number 23 and then square it \t: "
+ f1.andThen(f2).apply(23));
System.out.println("4. Double the number 2 and then square it \t: "
+ f1.andThen(f2).apply(2));
System.out.println("5. Double the number 20 and then square it \t: "
+ f1.andThen(f2).apply(20));
}
}
Output:
1. Double the number 5 and then square it : 100
2. Double the number 19 and then square it : 1444
3. Double the number 23 and then square it : 2116
4. Double the number 2 and then square it : 16
5. Double the number 20 and then square it : 1600
Example 2 – compose Function
- First, 2nd Function Computed i.e.; given Integer is Squared and
- Secondly, 1st Function is computed i.e.; Squared number is doubled and
- Final result is returned i.e.; final doubled number is printed into console
package net.bench.resources.function.example;
import java.util.function.Function;
public class ComposeFunction {
public static void main(String[] args) {
// 1 - lambda expression to double the given Integer using Function FI
Function<Integer, Integer> f1 = i -> 2*i;
// 2 - lambda expression to square the given Integer using Function FI
Function<Integer, Integer> f2 = i -> i*i;
// evaluating given Integer using Function joining
System.out.println("1. Square the number 5 and then double it \t: "
+ f1.compose(f2).apply(5));
System.out.println("2. Square the number 19 and double it \t: "
+ f1.compose(f2).apply(19));
System.out.println("3. Square the number 23 and double it \t: "
+ f1.compose(f2).apply(23));
System.out.println("4. Square the number 2 and double it \t: "
+ f1.compose(f2).apply(2));
System.out.println("5. Square the number 20 and double it \t: "
+ f1.compose(f2).apply(20));
}
}
Output:
1. Square the number 5 and then it : 50
2. Square the number 19 and double it : 722
3. Square the number 23 and double it : 1058
4. Square the number 2 and double it : 8
5. Square the number 20 and double it : 800
3. Function & Predicate Combining :
- We can combine both Function & Predicate Functional Interface for our requirements
- For example, if we want to evaluate Students based on some marks and then provide grades to them, then we combine Function as well Predicate to achieve this very easily
- In the below example, we are checking by iterating through each student that whether marks is greater than 60 using Predicate Functional Interface and then applying Function Functional Interface to calculate grades for them
package net.bench.resources.function.example;
import java.util.function.Function;
import java.util.function.Predicate;
class Student {
// member variables
String name;
int marks;
// public constructor
public Student(String name, int marks) {
super();
this.name = name;
this.marks = marks;
}
}
public class PredicateFunctionCombination {
public static void main(String[] args) {
// lambda expression to check student scored more than 60
Predicate<Student> p = s -> s.marks >= 60;
// lambda expression to find grade of Student supplied
Function<Student, String> f = student -> {
// alternatively, we can switch statement as well
if(student.marks >= 90)
return "Merit";
else if(student.marks >= 75)
return "Distinction";
else if(student.marks >= 60)
return "First class";
else if(student.marks >= 50)
return "Second class";
else if(student.marks >= 35)
return "Pass class";
else
return "Failed";
};
// create Student object for applying Predicate/Function
Student[] sArray = {
new Student("Vijay", 97),
new Student("Ajith", 78),
new Student("Vikram", 66),
new Student("Surya", 54),
new Student("Karthi", 43),
new Student("Arya", 31)
};
// iterate through check and find Student grade using Function FI
System.out.println("Name\tMarks\tGrade\n");
for(Student s : sArray) {
// Step 1 : check student marks using Predicate FI
if(p.test(s)) {
// Step 2 : prints grade based on marks using Function FI
System.out.println(s.name + "\t" + s.marks + "\t" + f.apply(s));
}
}
}
}
Output:
Name Marks Grade
Vijay 97 Merit
Ajith 78 Distinction
Vikram 66 First class
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html
- https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
- https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
- https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
Happy Coding !!
Happy Learning !!