Function Functional Interface in Java 8 – Definition, Syntax & Real-World Use Cases
The Function functional interface is a predefined interface introduced in Java 8 as part of the java.util.function package. It represents a function that accepts one input argument and produces one result. This interface is widely used in lambda expressions, Stream API operations, and functional programming.
A key feature of the Function interface is that it enables developers to define reusable transformation logic, where an input object is converted into another form. For example, converting a String into its length, a Student object into a grade, or an entity into a DTO.
Function is functional interface that takes one argument and produces a result ,
Syntax:
package com.test.rkdigitalschool.pred;
@FunctionalInterface
public class Function<T, R> {
R apply(T t);
}
- T: Type of input
- R: Type of the results
- apply(T t ) : Abstract Method that perform the operation
package com.test.rkdigitalschool.pred;
import java.util.function.Function;
public class Example {
public static void main(String[] args) {
Function<String, Integer> strLength = str -> str.length();
System.out.println(strLength.apply("ChatGPt Full course by Rkdigital school"));
}
}
- Function can take 2 type parameters first one represent input argument type and second one represent return type .
- Function interface defines one abstract method call apply() .
- Function can return any type of value .
Program1 : Write a program to remove space present in the given string by using function .
package com.test.rkdigitalschool.pred;
import java.util.function.Function;
public class FuncTest {
public static void main(String[] args) {
String s="Rkdigital school Navi Mumbai";
Function<String,String> f= s1 -> s1.replaceAll(" ", "");
System.out.println(f.apply(s));
}
}
Program2: Writ a program to find student grade by using function
Student.java
package com.test.rkdigitalschool.pred;
public class Student {
String name;
int marks;
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}
FunTest.java
package com.test.rkdigitalschool.pred;
import java.util.ArrayList;
import java.util.function.Function;
public class FunTest {
public static void main(String[] args) {
// Create student list
ArrayList<Student> sl = new ArrayList<>();
sl.add(new Student("Rohit", 85));
sl.add(new Student("Amit", 65));
sl.add(new Student("Sneha", 55));
sl.add(new Student("Neha", 40));
// Function to calculate grade
Function<Student, String> f = s -> {
int marks = s.marks;
if (marks >= 80) {
return "A [Distinction]";
} else if (marks >= 60) {
return "B [First Class]";
} else if (marks >= 50) {
return "C [Second Class]";
} else {
return "D [Failed]";
}
};
Predicate<Student> p=s.marks >=60;
// Apply function and print result
for (Student s : sl) {
if(p.test(s)){
System.out.println(
"Name: " + s.name +
", Marks: " + s.marks +
", Grade: " + f.apply(s)
);
}
}
}
}