The Java 8 Function
interface is a part of the java.util.function
package, and represents a single operation that takes an argument, performs some operation for that input argument, and produces a result. The R apply(T t)
method of the Function interface is used for this.
The main use of the Function
interface is to enable you to pass behavior as a parameter, making your code more flexible and expressive.
import java.util.function.Function;
public class FunctionUsage {
public static void main(String[] args) {
// Define a function to convert a string to uppercase
Function<String, String> toUpperCase = str -> str.toUpperCase();
// Apply the function
String input = "hello, world!";
String result = toUpperCase.apply(input);
System.out.println(result); // Output: HELLO, WORLD!
}
}
The Function
interface in Java 8 is a part of the java.util.function
package and has only one abstract method:
R apply(T t)
: This method takes an argument of typeT
, applies the function to it, and returns a result of typeR
.
However, the Function
interface also inherits the default methods from its parent interfaces (java.util.function.Interface
, java.util.function.BiFunction
). Here are the default methods available in the Function
interface:
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
: Returns a composed function that first applies the current function to its input and then applies theafter
function to the result.default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
: Returns a composed function that first applies thebefore
function to its input and then applies the current function to the result.
For the sake of completeness, here is the syntax of the Function
interface:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
// Implementation
}
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
// Implementation
}
}
The @FunctionalInterface
annotation indicates that the interface is intended to be used as a functional interface, meaning it can be used with lambda expressions and method references.
Different examples of using the Java 8 Function
interface.
- Example: Converting Fahrenheit to Celsius
import java.util.function.Function;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Function<Double, Double> fahrenheitToCelsius = f -> (f - 32) * 5/9;
double fahrenheit = 98.6;
double celsius = fahrenheitToCelsius.apply(fahrenheit);
System.out.println(fahrenheit + "°F is " + celsius + "°C");
}
}
Output: 98.6°F is 37.0°C
- Example: String Length Calculation
import java.util.function.Function;
public class StringLength {
public static void main(String[] args) {
Function<String, Integer> calculateLength = s -> s.length();
String text = "Java 8 is awesome!";
int length = calculateLength.apply(text);
System.out.println("Length of the string: " + length);
}
}
Output: Length of the string: 18
- Example: Doubling the Integer
import java.util.function.Function;
public class DoubleInteger {
public static void main(String[] args) {
Function<Integer, Integer> doubleNumber = num -> num * 2;
int input = 7;
int doubled = doubleNumber.apply(input);
System.out.println("Double of " + input + " is " + doubled);
}
}
Output: Double of 7 is 14
- Example: Adding Prefix to a String
import java.util.function.Function;
public class AddPrefix {
public static void main(String[] args) {
Function<String, String> addPrefix = str -> "Prefix_" + str;
String input = "example";
String result = addPrefix.apply(input);
System.out.println("Result: " + result);
}
}
Output: Result: Prefix_example
- Example: Squaring Doubles
import java.util.function.Function;
public class SquareDouble {
public static void main(String[] args) {
Function<Double, Double> square = num -> num * num;
double value = 3.5;
double squared = square.apply(value);
System.out.println("Square of " + value + " is " + squared);
}
}
Output: Square of 3.5 is 12.25
These examples showcase different use cases for the Java 8 Function
interface, demonstrating how it can be used to perform various transformations and calculations.
Let’s see a few objective questions related to Java 8 Function interface.
Question 1: What is the primary purpose of the Java 8 Function interface?
A) To represent a unary function that accepts one input and produces one output.
B) To represent a binary function that accepts two inputs and produces one output.
C) To represent a function that accepts multiple inputs and produces multiple outputs.
D) To represent a void function that performs side effects.
Question 2: Which method of the Function interface is used to apply the function and obtain the result?
A) apply()
B) execute()
C) perform()
D) invoke()
Question 3: How can you compose two Function instances to create a new Function that applies the second function to the result of the first?
A) Using the andThen() method
B) Using the compose() method
C) Using the combine() method
D) Using the merge() method
Question 4: What is the return type of the apply() method in the Function interface?
A) void
B) boolean
C) Object
D) The same as the output type specified in the generic type parameters of the Function.
Answers:-
1. Answer: A) To represent a unary function that accepts one input and produces one output.
2. Answer: A) apply()
3. Answer: A) Using the andThen() method
4. Answer: D) The same as the output type specified in the generic type parameters of the Function.
That’s all about Java 8 Function interface Examples.
Other Java 8 examples.
- Difference between Anonymous Inner Class and Lambda Expression
- Java 8 Comparator comparing() example
- Java 8 Lambda Expressions Examples
- Write a program to find the nth Highest Salary using Java…
- Java 8 Functional Interface Examples
- Java 8 Supplier Examples
- Java 8 Consumer Examples
- Java 8 Predicate examples
- Java 8 default methods examples
- Java 8 Collection vs Stream
- Java 8 static methods examples