Java LongFunction Interface with examples

 206 total views,  1 views today

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

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

What is the use of LongFunction?

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

Example

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

	interface Operation {
		long add(long i);
	}
}

When you look at the above example, we have a function interface with an abstract method which accepts one argument of type long 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 LongFunction interface. Let now see in-depth details on Java LongFunction Interface with examples.

LongFunction Interface

@FunctionalInterface
public interface LongFunction<R>

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

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

Method description

R apply(long value)
value - the input argument

Example of LongFunction interface using lambda

public class StaticReference {
	public static void main(String[] args) {
		LongFunction<Long> function = (long i) -> {
			return i + i;
		};
		function.apply(1);
	}
}

Example of LongFunction interface using a Method reference

public class StaticReference {
	public static void main(String[] args) {
		LongFunction<Long> function = StaticReference::add;
		function.apply(1);
	}

	static long add(long i) {
		return i + i;
	}
}

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

References

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