eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

Fugue is a Java library by Atlassian; it’s a collection of utilities supporting Functional Programming.

In this write-up, we’ll focus on and explore the most important Fugue’s APIs.

2. Getting Started With Fugue

To start using Fugue in our projects, we need to add the following dependency:

<dependency>
    <groupId>io.atlassian.fugue</groupId>
    <artifactId>fugue</artifactId>
    <version>4.5.1</version>
</dependency>

We can find the most recent version of Fugue over on Maven Central.

3. Option

Let’s start our journey by looking at the Option class which is Fugue’s answer to java.util.Optional.

As we can guess by the name, Option’s a container representing a potentially absent value.

In other words, an Option is either Some value of a certain type or None:

Option<Object> none = Option.none();
assertFalse(none.isDefined());

Option<String> some = Option.some("value");
assertTrue(some.isDefined());
assertEquals("value", some.get());

Option<Integer> maybe = Option.option(someInputValue);

3.1. The map Operation

One of the standard Functional Programming APIs is the map() method which allows applying a provided function to underlying elements.

The method applies the provided function to the Option‘s value if it’s present:

Option<String> some = Option.some("value") 
  .map(String::toUpperCase);
assertEquals("VALUE", some.get());

3.2. Option and a Null Value

Besides naming differences, Atlassian did make a few design choices for Option that differ from Optional; let’s now look at them.

We cannot directly create a non-empty Option holding a null value:

Option.some(null);

The above throws an exception.

However, we can get one as a result of using the map() operation:

Option<Object> some = Option.some("value")
  .map(x -> null);
assertNull(some.get());

This isn’t possible when simply using java.util.Optional.

3.3. Option Is Iterable

Option can be treated as a collection that holds maximum one element, so it makes sense for it to implement the Iterable interface.

This highly increases the interoperability when working with collections/streams.

And now, for example, can be concatenated with another collection:

Option<String> some = Option.some("value");
Iterable<String> strings = Iterables
  .concat(some, Arrays.asList("a", "b", "c"));

3.4. Converting Option to Stream

Since an Option is an Iterable, it can be converted to a Stream easily too.

After converting, the Stream instance will have exactly one element if the option is present, or zero otherwise:

assertEquals(0, Option.none().toStream().count());
assertEquals(1, Option.some("value").toStream().count());

3.5. java.util.Optional Interoperability

If we need a standard Optional implementation, we can obtain it easily using the toOptional() method:

Optional<Object> optional = Option.none()
  .toOptional();
assertTrue(Option.fromOptional(optional)
  .isEmpty());

3.6. The Options Utility Class

Finally, Fugue provides some utility methods for working with Options in the aptly named Options class.

It features methods such as filterNone for removing empty Options from a collection, and flatten for turning a collection of Options into a collection of enclosed objects, filtering out empty Options.

Additionally, it features several variants of the lift method that lifts a Function<A,B> into a Function<Option<A>, Option<B>>:

Function<Integer, Integer> f = (Integer x) -> x > 0 ? x + 1 : null;
Function<Option<Integer>, Option<Integer>> lifted = Options.lift(f);

assertEquals(2, (long) lifted.apply(Option.some(1)).get());
assertTrue(lifted.apply(Option.none()).isEmpty());

This is useful when we want to pass a function which is unaware of Option to some method that uses Option.

Note that, just like the map method, lift doesn’t map null to None:

assertEquals(null, lifted.apply(Option.some(0)).get());

4. Either for Computations With Two Possible Outcomes

As we’ve seen, the Option class allows us to deal with the absence of a value in a functional manner.

However, sometimes we need to return more information than “no value”; for example, we might want to return either a legitimate value or an error object.

The Either class covers that use case.

An instance of Either can be a Right or a Left but never both at the same time.

By convention, the right is the result of a successful computation, while the left is the exceptional case.

4.1. Constructing an Either

We can obtain an Either instance by calling one of its two static factory methods.

We call right if we want an Either containing the Right value:

Either<Integer, String> right = Either.right("value");

Otherwise, we call left:

Either<Integer, String> left = Either.left(-1);

Here, our computation can either return a String or an Integer.

4.2. Using an Either

When we have an Either instance, we can check whether it’s left or right and act accordingly:

if (either.isRight()) {
    ...
}

More interestingly, we can chain operations using a functional style:

either
  .map(String::toUpperCase)
  .getOrNull();

4.3. Projections

The main thing that differentiates Either from other monadic tools like Option, Try, is the fact that often it’s unbiased. Simply put, if we call the map() method, Either doesn’t know if to work with Left or Right side.

This is where projections come in handy.

Left and right projections are specular views of an Either that focus on the left or right value, respectively:

either.left()
  .map(x -> decodeSQLErrorCode(x));

In the above code snippet, if Either is Left, decodeSQLErrorCode() will get applied to the underlying element. If Either is Right, it won’t. Same the other way around when using the right projection.

4.4. Utility Methods

As with Options, Fugue provides a class full of utilities for Eithers, as well, and it’s called just like that: Eithers.

It contains methods for filtering, casting and iterating over collections of Eithers.

5. Exception Handling with Try

We conclude our tour of either-this-or-that data types in Fugue with another variation called Try.

Try is similar to Either, but it differs in that it’s dedicated for working with exceptions.

Like Option and unlike Either, Try is parameterized over a single type, because the “other” type is fixed to Exception (while for Option it’s implicitly Void).

So, a Try can be either a Success or a Failure:

assertTrue(Try.failure(new Exception("Fail!")).isFailure());
assertTrue(Try.successful("OK").isSuccess());

5.1. Instantiating a Try

Often, we won’t be creating a Try explicitly as a success or a failure; rather, we’ll create one from a method call.

Checked.of calls a given function and returns a Try encapsulating its return value or any thrown exception:

assertTrue(Checked.of(() -> "ok").isSuccess());
assertTrue(Checked.of(() -> { throw new Exception("ko"); }).isFailure());

Another method, Checked.lift, takes a potentially throwing function and lifts it to a function returning a Try:

Checked.Function<String, Object, Exception> throwException = (String x) -> {
    throw new Exception(x);
};
        
assertTrue(Checked.lift(throwException).apply("ko").isFailure());

5.2. Working With Try

Once we have a Try, the three most common things we might ultimately want to do with it are:

  1. extracting its value
  2. chaining some operation to the successful value
  3. handling the exception with a function

Besides, obviously, discarding the Try or passing it along to other methods, the above three aren’t the only options that we have, but all the other built-in methods are just a convenience over these three.

5.3. Extracting the Successful Value

To extract the value, we use the getOrElse method:

assertEquals(42, failedTry.getOrElse(() -> 42));

It returns the successful value if present, or some computed value otherwise.

There is no getOrThrow or similar, but since getOrElse doesn’t catch any exception, we can easily write it:

someTry.getOrElse(() -> {
    throw new NoSuchElementException("Nothing to get");
});

5.4. Chaining Calls After Success

In a functional style, we can apply a function to the success value (if present) without extracting it explicitly first.

This is the typical map method we find in Option, Either and most other containers and collections:

Try<Integer> aTry = Try.successful(42).map(x -> x + 1);

It returns a Try so we can chain further operations.

Of course, we also have the flatMap variety:

Try.successful(42).flatMap(x -> Try.successful(x + 1));

5.5. Recovering From Exceptions

We have analogous mapping operations that work with the exception of a Try (if present), rather than its successful value.

However, those methods differ in that their meaning is to recover from the exception, i.e. to produce a successful Try in the default case.

Thus, we can produce a new value with recover:

Try<Object> recover = Try
  .failure(new Exception("boo!"))
  .recover((Exception e) -> e.getMessage() + " recovered.");

assertTrue(recover.isSuccess());
assertEquals("boo! recovered.", recover.getOrElse(() -> null));

As we can see, the recovery function takes the exception as its only argument.

If the recovery function itself throws, the result is another failed Try:

Try<Object> failure = Try.failure(new Exception("boo!")).recover(x -> {
    throw new RuntimeException(x);
});

assertTrue(failure.isFailure());

The analogous to flatMap is called recoverWith:

Try<Object> recover = Try
  .failure(new Exception("boo!"))
  .recoverWith((Exception e) -> Try.successful("recovered again!"));

assertTrue(recover.isSuccess());
assertEquals("recovered again!", recover.getOrElse(() -> null));

6. Other Utilities

Let’s now have a quick look at some of the other utilities in Fugue, before we wrap it up.

6.1. Pairs

A Pair is a really simple and versatile data structure, made of two equally important components, which Fugue calls left and right:

Pair<Integer, String> pair = Pair.pair(1, "a");
        
assertEquals(1, (int) pair.left());
assertEquals("a", pair.right());

Fugue doesn’t provide many built-in methods on Pairs, besides mapping and the applicative functor pattern.

However, Pairs are used throughout the library and they are readily available for user programs.

The next poor person’s implementation of Lisp is just a few keystrokes away!

6.2. Unit

Unit is an enum with a single value which is meant to represent “no value”.

It’s a replacement for the void return type and Void class, that does away with null:

Unit doSomething() {
    System.out.println("Hello! Side effect");
    return Unit();
}

Quite surprisingly, however, Option doesn’t understand Unit, treating it like some value instead of none.

6.3. Static Utilities

We have a few classes packed full of static utility methods that we won’t have to write and test.

The Functions class offers methods that use and transform functions in various ways: composition, application, currying, partial functions using Option, weak memoization et cetera.

The Suppliers class provides a similar, but more limited, collection of utilities for Suppliers, that is, functions of no arguments.

Iterables and Iterators, finally, contain a host of static methods for manipulating those two widely used standard Java interfaces.

7. Conclusion

In this article, we’ve given an overview of the Fugue library by Atlassian.

We haven’t touched the algebra-heavy classes like Monoid and Semigroups because they don’t fit in a generalist article.

However, you can read about them and more in the Fugue javadocs and source code.

We also haven’t touched on any of the optional modules, that offer for example integrations with Guava and Scala.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)