java.util.function library

Posted on Posted in Architect, Java

As in previous topic, we can use functional interfaces to use in lambda expression see topic on: Java 8 interfaces

However Java 8 goes on more to provide us mechanism to easier create lambda expressions. See java.util.function library. No need to create an functional interface and just overwrite existing ones in this library.

This library can be divided in to four sections:

Consumers

Consumers are interfaces that focuses on accepting parameters. for example: BiConsumer – as the api reads, this accepts two arguments and produces no result:

The same logic applies to all the *Consumer  in the library like DoubleConsumer, LongConsumer, and so forth.

Functions

Functions are interfaces that are focused on doing accepting a parameter and returning a result. for example: BiFunction – as the api reads, accepts two arguments and returns one result we can use it as below:

The same logic applies to all the *Function in the library like DoubleToLongFunctionLongToDoubleFunction, and so forth.

Supplier

In contrast, Supplier methods just returns an object without an parameters:

This applies to all *Supplier methods, like IntSupplier, BooleanSupplier, and so forth.

Operator

Finally we have UnaryOperator methods in the library, it is much similar to consumer, but in a way it just accepts an object and returns that same type.

The best way to use UnaryOperators are for when using objects you have created, see example below.

In this case I have created a People class, and the output will also be the same class:

Same applies to other *Operators method in the library however the others have a predefined data type. for example DoubleUnaryOperator, IntUnaryOperator, and so forth.

Leave a Reply