Java IntFunction Interface with examples

 310 total views,  2 views today

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

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

What is the use of IntFunction?

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

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

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

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

IntFunction Interface

@FunctionalInterface
public interface IntFunction<R>

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

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

Method description

R apply(int value)
value - the input argument

Example of IntFunction interface using lambda

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

Example of IntFunction interface using a Method reference

public class StaticReference {
	public static void main(String[] args) {
		IntFunction<Integer> function = StaticReference::print;
		function.apply(1);
	}

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

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

References

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.