How to pass function as a parameter in a method in Java 8?

Here, we are going to see the magic that Java 8 brought to all of us in the form of ‘higher order functions’ or first-class functions. Higher order functions are the functions which takes another function as an argument or throw a function after the execution. In this post, we will see a most basic & simple example to understand ‘how to pass a function as a parameter or argument into a method?’.

Basically, you can pass any object as a parameter to a method. But, having said that, first, we would need to learn how to store a function in an object.

Simplest example of Higher Order Function (passing one function to another as an parameter or argument) in Java 8...!!! Click To Tweet

Java 8 introduced ‘Function Interface’ which takes one argument and returns one object. See it’s signature below:

  • Type Parameters:
    T – the type of the input to the function
    R – the type of the result of the function

Example: Addition/Sum operation using Higher Order Function

This is the simplest example on higher order function to make you understand how to pass a function as an parameter to another method. 

 

Let’s understand the code:

1. First, create a function which takes one integer and return an integer after adding 1 to it. 

2. Pass that function into another method (sum) with another integer on the side (value)

3. Now, here is the magic of a default ‘apply’ method of ‘function interface’ which operates the logical operation specified in step 1 with the value being passed. So, here in this case, 5 is the value and operation is value -> value+1 i.e 5 -> 5+1

I hope you understand now, what will come back as an output. That would be 6. 

This is how, higher order function works. This is simplest example, I’ve provided you to make you clear enough on the working of functions passing into other functions. 

 

Simplest example of Higher Order Function (passing one function to another as an argument or parameter) in Java 8...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References:

 

Related Posts:

[wcp-carousel id=”5342″]

Promotional Content:

Loading RSS Feed

Leave a Reply

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

Facebook Twitter Instagram YouTube