Java DoubleFunction Interface with examples

 211 total views,  2 views today

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

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

What is the use of DoubleFunction?

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

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

	interface Operation {
		double print(double i);
	}
}

When you look at the above example, we have a function interface with an abstract method which accepts one argument of type double 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 DoubleFunction interface.

Let now see in-depth details on Java DoubleFunction Interface with examples.

DoubleFunction Interface

@FunctionalInterface
public interface DoubleFunction

DoubleFunction interface contains an operation that accepts one input argument of type double and returns a result of type double.

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

Method description

R apply(double value)
value - the input argument

Example of DoubleFunction interface using lambda

public class StaticReference {
	public static void main(String[] args) {
		DoubleFunction<Double> funtion = (double i) -> {
			return i + i;
		};
		funtion.apply(1.0);
	}

	interface Operation {
		double print(double i);
	}
}

Example of DoubleFunction interface using Method reference

public class StaticReference {
	public static void main(String[] args) {
	DoubleFunction<Double> function = StaticReference::print;
		function.apply(1.0);
	}

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

If you want to write a lambda expression with one argument of type double and a result, please use Java DoubleFunction interface.

References

Java 8 DoubleFunction 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!.