A Java 21 library designed to enhance your functional programming experience by providing a collection of robust and thread-safe classes for handling common functional patterns.
This library is built around polymorphic execution — a core design principle that allows you to write business logic once and execute it in different ways without changing your code.
The Result<T> sealed interface serves as the foundation, with three implementations:
DirectResult<T>: Synchronous, immediate execution (for simple, fast operations)AsyncResult<T>: Asynchronous execution usingCompletableFuture(for I/O-bound or long-running tasks)LazyResult<T>: Deferred execution (for expensive computations that should only run when needed)
All three implement the same Result<T> interface, so your functional pipelines (map, flatMap, etc.) remain identical regardless of the execution model. This means you can:
- Start with synchronous code for simplicity
- Switch to async when you need non-blocking behavior
- Use lazy evaluation for performance optimization
- Without changing a single line of your business logic
This approach provides flexibility without complexity, making it ideal for applications that need to handle a mix of synchronous and asynchronous operations.
Simple, immutable generic containers for holding two (Pair) values of any type.
Usage:
// Create a Pair
Pair<String, Integer> pair = Pair.of("Age", 30);
String key = pair.getLeft(); // "Age"
Integer value = pair.getRight(); // 30An interface that represents the result of an operation, which can be either a success (holding a value of type T) or a failure (holding a Failure object). It combines the safety of Optional with the error-handling capabilities of Either.
Unlike most libraries that force you to choose a different API for sync and async code (e.g., Optional vs CompletableFuture), this library provides a unified abstraction. You can write your business logic against the Result interface, and it remains agnostic to how or when the computation occurs:
DirectResult<T>: Synchronous, immediate execution.AsyncResult<T>: Asynchronous execution (non-blocking).LazyResult<T>: Deferred execution (computed only when accessed).
This allows you to swap execution models (e.g., moving a heavy calculation from sync to async) without changing the functional pipelines (map, flatMap) of your service.
Result<Integer> success = DirectResult.ok(100);
Result<Integer> failure = DirectResult.failure(new DescriptionFailure("Something went wrong"));
Result<String> finalResult = success
.map(value -> value * 2) // Returns Result.ok(200)
.flatMap(value -> DirectResult.ok("Final value: " + value));
String resultString = finalResult.getOrThrow(); // "Final value: 200"
Integer errorCase = failure.orElse(f -> -1); // -1When performing asynchronous operations, you are responsible for providing and managing an ExecutorService. This gives you full control over your application's concurrency model.
ExecutorService executor = Executors.newFixedThreadPool(4);
try {
Supplier<Integer> longRunningTask = () -> {
// ... some computation ...
return 200;
};
Result<Integer> asyncResult = AsyncResult.create(executor, longRunningTask);
Result<String> finalAsyncResult = asyncResult
.map(value -> "The value is: " + value);
System.out.println(finalAsyncResult.getOrThrow()); // "The value is: 200"
} finally {
executor.shutdown();
}LazyResult defers the execution of the supplier and all chained functions until the value is explicitly requested (e.g., via getOrThrow()). It also memoizes the result once computed.
AtomicInteger counter = new AtomicInteger(0);
Result<Integer> lazy = LazyResult.create(() -> {
counter.incrementAndGet();
return 10;
});
Result<Integer> mapped = lazy.map(v -> v * 2);
System.out.println(counter.get()); // 0
System.out.println(mapped.getOrThrow()); // 20
System.out.println(counter.get()); // 1
// The result is memoized; subsequent calls won't re-run the supplier
System.out.println(lazy.getOrThrow()); // 10
System.out.println(counter.get()); // 1- Fun: A functional interface representing a function that takes one argument and returns a result.
- Fun2: A functional interface similar to
Fun, but representing a function that takes two arguments and returns a result.
Usage:
// Fun example: squaring a number
Fun<Integer, Integer> square = Fun.from(i -> i * i);
Result<Integer> result = square.apply(2);
System.out.println(result.getOrThrow()); // 4
// Fun2 example: adding two numbers
Fun2<Integer, Integer, Integer> add = Fun2.from((a, b) -> a + b);
Result<Integer> sumResult = add.apply(3, 5);
System.out.println(sumResult.getOrThrow()); // 8
// Fun example: composition
Fun<Integer, Integer> twoTimes = Fun.from(a -> 2 * a);
Fun<Integer, Integer> threeTimes = Fun.from(a -> 3 * a);
Fun<Integer, Integer> sixTimes = Fun.compose(twoTimes, threeTimes);
System.out.println(sixTimes.apply(5).getOrThrow()); //30
// Fun2 example: curry
Fun2<Integer, Integer, Integer> sum = Fun2.from(Integer::sum);
Fun<Integer, Integer> plus10 = sum.curry(10);
System.out.println(plus10.apply(2).getOrThrow()); //12A simple yet powerful pattern matcher that evaluates an input value against a series of conditions and returns a Result with the output value. Use create() to start building a matcher, on() to add match cases, and resultFor() to evaluate an input.
Usage:
Matcher<Integer, String> numberMatcher = Matcher.create(Integer.class, String.class)
.on(i -> i == 1, i -> "One")
.on(i -> i == 2, i -> "Two")
.on(i -> i > 2, i -> "More than two");
Result<String> result1 = numberMatcher.resultFor(1); // Result.ok("One")
Result<String> result2 = numberMatcher.resultFor(5); // Result.ok("More than two")
Result<String> result3 = numberMatcher.resultFor(0); // Result with MatcherNotFoundFailureA utility class for validating values against one or multiple criteria. It returns a Result that either contains the valid value or a Failure indicating which validation rule failed.
Usage:
Failure tooShort = new DescriptionFailure("Must be at least 5 characters");
Failure noNumber = new DescriptionFailure("Must contain a number");
// Validate a value against multiple rules using Pairs
Result<String> result = Validation.validate("pass1",
Pair.of(tooShort, s -> s.length() >= 5),
Pair.of(noNumber, s -> s.matches(".*\\d.*"))
);
// Single validation
Result<Integer> ageResult = Validation.validate(25,
new DescriptionFailure("Must be an adult"),
age -> age >= 18
);A thread-safe container that implements the Actor model. It holds a value and ensures that all modifications to that value are executed sequentially and safely in a concurrent environment using a non-blocking queue.
Usage:
ExecutorService executor = Executors.newFixedThreadPool(4);
Agent<Integer> counter = Agent.create(executor, 0);
for (int i = 0; i < 1000; i++) {
//Update functions are executed async in order
Agent.update(counter, value -> value + 1);
}
Result<Integer> result = Agent.get(counter);
System.out.println(result.getOrThrow()); // 1000
// Set a maximum size of the allowed functions in the queue
Agent<Integer> boundedCounter = Agent.create(executor, 0, 100);Java 21, no more dependencies.
mvn clean verify org.pitest:pitest-maven:mutationCoverage
Check deployments here: https://central.sonatype.com/publishing/deployments
To create deploy to be release: mvn clean deploy -Prelease -Pgpg
This is the setup needed in .m2/settings.xml
<settings>
<servers>
<server>
<id>central</id>
<username><-- USERNAME --></username>
<password><-- PASSWORD --></password>
</server>
</servers>
<profiles>
<profile>
<id>gpg</id>
<properties>
<gpg.executable>gpg</gpg.executable>
<gpg.passphrase><-- PASSPHRASE --></gpg.passphrase>
</properties>
</profile>
</profiles>
</settings>