A generic Lazy
class in java
A wrapper for a Supplier
function that evaluates it lazily when it is first needed,
remembering the result so the wrapped supplier does not get called again.
Lazy
wraps the Supplier
functional interface.
This is often recurring functionality that should have been provided out of the box by the JDK when lambda's were introduced in Java 8.
Fortunately, it's not very difficult to create, so that's what we did.
A small example of how this class can be used:
public class Example {
private final Lazy<Expensive> expensive = Lazy.lazy(Expensive::create);
}
This declares a lazy expensive
variable without creating an expensive object yet.
Only when get()
is called for the first time, the Expensive.create()
method is called.
All subsequent invocations will return the same instance of Expensive
.
Lazy provides the following methods:
isAvailable
returning whether the lazy value is already available.map
applies a function on the lazy result.flatMap
applies a function that itself returns a supplier.ifAvailable
runs a function only if the lazy value is already available.
Please refer to the Lazy class documentation for full descriptions.
Add the following dependency to your project or download it directly from github:
<dependency>
<groupId>nl.talsmasoftware</groupId>
<artifactId>lazy4j</artifactId>
<version>[see maven badge]</version>
</dependency>
compile 'nl.talsmasoftware:lazy4j:[see maven-central badge]'
libraryDependencies += "nl.talsmasoftware" % "lazy4j" % "[see maven-central badge]"