Java Function Interface with examples

 205 total views,  1 views today

Welcome to Java 8 Series. In this tutorial, you will learn about the Java Function Interface with examples.

Function is a Functional interface introduced as part of Java 8. It is available in java.util.function package.

What is the use of Function interface?

Consider a case where we need to write a lambda expression which accepts one input and perform an operation on that input and returns a result.

public class StaticReference {
	public static void main(String[] args) {
		Operation ops = (String i) -> {
			return i+i;
		};
		String result = ops.print("aa");
		System.out.println(result);
	}

}

interface Operation {
	String print(String i);
}

When you look at the above example, we have a function interface with an abstract method which accepts one argument and returns a result. So a lambda expression needs a target type which needs to be a functional interface and in this example, it is Operation interface.

Instead of creating our own function interface for this scenario, Java has provided us a Function interface.

Let us now learn in-depth details about Java Function Interface with examples.

Function Interface

@FunctionalInterface
public interface Function<T,R>

Function interface contains an operation that accepts one input argument and returns a result.

It is a functional interface and the functional method is apply(Object).

Method description

R apply(T t)
t - the function argument

Example of Function interface using lambda

public class StaticReference {
	public static void main(String[] args) {
		Function<String, String> function = (String i) -> {
			return i + i;
		};
		function.apply("apple");
	}

}

Example of Function interface using Method reference

public class StaticReference {
	public static void main(String[] args) {
	Function<String, String> function = StaticReference::print;
		function.apply("apple");
	}

	static String print(String i) {
		return i + i;
	}

}

If you want to write a lambda expression with one argument and a result, please use Java Function interface.

References

Java 8 Function Interface official documentation

Thanks for reading. Please a comment and give us a thumbs up.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.