Table of Contents
In this post, we will see about java.util.function.Function functional interface.
java.util.function.Function is part of java.util.function package. There are some inbuilt functional interfaces in java.util.function which you can use if functional interface matches with your requirement.
java.util.function.Function is a functional interface which takes input single argument T and returns result R.
It has an abstract method as below.
1 2 3 |
R apply(T t) |
Let’s understand with the help of an example.
Java 8 function example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog.java8; import java.util.function.Function; public class java8FunctionExample { public static void main(String[] args) { Function<Integer,Double> functionSqrt = n -> Math.sqrt(n); System.out.println("Square root of 49: "+functionSqrt.apply(49)); System.out.println("Square root of 68: "+functionSqrt.apply(68)); } } |
When you run above program, you will get below output:
Square root of 68: 8.246211251235321
andThen function
It is default function and returns a composed function that first applies this function to its input, and then applies the after function to the result.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog.java8; import java.util.function.Function; public class java8FunctionExample { public static void main(String[] args) { Function<Integer,Double> functionSqrt = n -> Math.sqrt(n); Function<Double,Double> functionDouble = n -> 2.0*n; double result=functionSqrt.andThen(functionDouble).apply(30); System.out.println("Result with andThen: "+result); } } |
compose function
It is default function and returns a composed function that first applies the before function to its input, and then applies this function to the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog.java8; import java.util.function.Function; public class java8FunctionExample { public static void main(String[] args) { Function<Integer,Double> functionSqrt = n -> Math.sqrt(n); Function<Double,Double> functionDouble = n -> 2.0*n; double result2=functionDouble.compose(functionSqrt).apply(30); System.out.println("Result with compose: "+result2); } } |
Use of java.util.function.Function in Stream’s map method
If you notice Stream’s map methods takes Function as input because map function requires a functional interface which takes input single argument T and returns result R and java.util.function.Function serves the purpose for Stream’s map method
1 2 3 |
<R> Stream<R> map(Function<? super T,? extends R>mapper) |
That’s all about Java 8- java.util.function.Function example.