Java 8 – java.util.function.Function example

Previous
Next

In this post, we will see about java.util.function.Function functional interface.

java.util.function.Function is part of java.util.function package. There are some inbuilt functional interfaces in java.util.function which you can use if functional interface matches with your requirement.

java.util.function.Function is a functional interface which takes input single argument T and returns result R.

It has an abstract method as below.

Let’s understand with the help of an example.

Java 8 function example

When you run above program, you will get below output:

Square root of 49: 7.0
Square root of 68: 8.246211251235321

andThen function

It is default function and returns a composed function that first applies this function to its input, and then applies the after function to the result.

For example:

Result with andThen: 10.954451150103322

compose function

It is default function and returns a composed function that first applies the before function to its input, and then applies this function to the result.

Result with andThen: 10.954451150103322

Use of java.util.function.Function in Stream’s map method

If you notice Stream’s map methods takes Function as input because map function requires a functional interface which takes input single argument T and returns result R and java.util.function.Function serves the purpose for Stream’s map method

That’s all about Java 8- java.util.function.Function example.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog