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.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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. Overview

In this tutorial, we’re going to discuss Monads and their definition using Java. The idea is to understand the concept, what problems it addresses, and how the Java language implements it.

By the end of it, we hope one can understand the Monads and how to make the most of it.

2. The Concept

The Monad is a design pattern popular in the functional programming world. However, it actually originated from a mathematical field called Category Theory. This article will focus on Monad’s definition of the software engineering field. Although both definitions have many similarities, the software one and the field’s jargon are more relevant to our context.

In short, a general concept is an object that can map itself to different results based on transformations.

3. The Design Pattern

Monads are containers or structures that encapsulate values and computations. They must have two basic operations:

  • Unit: monads represent a type that wraps a given value, and this operation is responsible for wrapping the value. For example, in Java, this operation can accept values from different types just by leveraging generics
  • Bind: This operation allows transformation to be executed using the held value and returns a new monad value (a value wrap in the monad type)

Nonetheless, there are some properties that a monad has to obey:

  • Left identity: when applying to a monad, it should yield the same outcome as applying the transformation to the held value
  • Right identity: when sending a monad transformation (convert the value to a monad), the yield outcome must be the same as wrapping the value in a new monad
  • Associativity: when chaining transformations, it should not matter how transformations are nested

One of the challenges of functional programming is to allow pipelining of such operations without losing readability. This is one of the reasons for adopting the concept of monads. The Monad is fundamental to the functional paradigm and helps implement declarative programming.

4. Java Interpretation

Java 8 implemented the Monad design pattern through classes like OptionalHowever, let’s first look at a code before the addition of the Optional class:

public class MonadSample1 {
    //... 
    private double multiplyBy2(double n) {
        return n * 2;
    }

    private double divideBy2(double n) {
        return n / 2;
    }

    private double add3(double n) {
        return n + 3;
    }

    private double subtract1(double n) {
        return n - 1;
    }

    public double apply(double n) {
        return subtract1(add3(divideBy2(multiplyBy2(multiplyBy2(n)))));
    }
    //... 
public class MonadSampleUnitTest {
    //...
    @Test
    public void whenNotUsingMonad_shouldBeOk() {
        MonadSample1 test = new MonadSample1();
        Assert.assertEquals(6.0, test.apply(2), 0.000);
    }
    //... 
}

As we can observe, the apply method looks quite hard to read, but what would be the alternative to it? Maybe the following:

public class MonadSample2 {
    //... 
    public double apply(double n) { 
        double n1 = multiplyBy2(n); 
        double n2 = multiplyBy2(n1); 
        double n3 = divideBy2(n2); 
        double n4 = add3(n3); 
        return subtract1(n4); 
    } 
    //...
public class MonadSampleUnitTest {
    //...
    @Test
    public void whenNotUsingMonadButUsingTempVars_shouldBeOk() {
        MonadSample2 test = new MonadSample2();
        Assert.assertEquals(6.0, test.apply(2), 0.000);
    }
    //...
}

This seems better, but it still looks too verbose. So let’s see what it would be like using Optional:

public class MonadSample3 {
    //...
    public double apply(double n) {
        return Optional.of(n)
          .flatMap(value -> Optional.of(multiplyBy2(value)))
          .flatMap(value -> Optional.of(multiplyBy2(value)))
          .flatMap(value -> Optional.of(divideBy2(value)))
          .flatMap(value -> Optional.of(add3(value)))
          .flatMap(value -> Optional.of(subtract1(value)))
          .get();
    }
    //...
public class MonadSampleUnitTest {
    //...
    @Test
    public void whenUsingMonad_shouldBeOk() {
        MonadSample3 test = new MonadSample3();
        Assert.assertEquals(6.0, test.apply(2), 0.000);
    }
    //...
}

The code above seems cleaner. On the other hand, this design allows developers to apply as many subsequent transformations as needed without sacrificing readability and reducing the verboseness of the temporary variables declarations.

There is more; imagine if any of those functions could produce null values. In such a case, we would have to add validation before each transformation, making the code more verbose. That is actually the primary purpose of the Optional class. The idea was to avoid working with null and provide an easy-to-use way to apply transformations to objects so that when they aren’t null, a series of declarations will be executed in a null-safe manner. It’s also possible to check if the value wrapped by the Optional is empty or not (has a value null).

4.1. Optional Caveats

As described at the beginning, Monads need to have some operations and properties, so let’s look at those properties in the Java implementation. First, why not check the operations that a Monad must have:

  • For Unit operations, Java offers different flavors like Optional.of() and Optional.nullable(). As we may imagine, one accepts null values, and the other does not
  • As for the Bind function, Java offers the Optional.flatMap() operation, introduced in the code examples

A feature that is not in the definition of a Monad is the map operation. It is a transformation and chain operation similar to flatMap. The difference between the two is that the map operation receives a transformation that returns a raw value to be wrapped internally by the API. While the flatMap already returns a wrapped value that the API returns to form the pipeline.

Now, let’s examine the properties of the Monad:

public class MonadSample4 {
    //... 
    public boolean leftIdentity() {
         Function<Integer, Optional> mapping = value -> Optional.of(value + 1);
         return Optional.of(3).flatMap(mapping).equals(mapping.apply(3));
     }

     public boolean rightIdentity() {
         return Optional.of(3).flatMap(Optional::of).equals(Optional.of(3));
     }

     public boolean associativity() {
         Function<Integer, Optional> mapping = value -> Optional.of(value + 1);
         Optional leftSide = Optional.of(3).flatMap(mapping).flatMap(Optional::of);
         Optional rightSide = Optional.of(3).flatMap(v -> mapping.apply(v).flatMap(Optional::of));
         return leftSide.equals(rightSide);
     }
     //... 
public class MonadSampleUnitTest {
    //...  
    @Test
    public void whenTestingMonadProperties_shouldBeOk() {
        MonadSample4 test = new MonadSample4();
        Assert.assertEquals(true, test.leftIdentity());
        Assert.assertEquals(true, test.rightIdentity());
        Assert.assertEquals(true, test.associativity());
    }
    //...
}

At first glance, all properties seem to comply with the requirements, and Java has a proper Monad implementation, but this is not actually the case. Let’s try one more test:

class MonadSample5 {
    //...
    public boolean fail() {
        Function<Integer, Optional> mapping = value -> Optional.of(value == null ? -1 : value + 1);
        return Optional.ofNullable((Integer) null).flatMap(mapping).equals(mapping.apply(null));
    }
    //...
class MonadSampleUnitTest {
    @Test
    public void whenBreakingMonadProperties_shouldBeFalse() {
        MonadSample5 test = new MonadSample5();
        Assert.assertEquals(false, test.fail());
    }
    //...
}

As observed, the left identity property from Monad was broken. Actually, this seems to be a conscious decision, as per this discussion. One member of the JDK team says Optional has a narrower scope than other languages, and they don’t intend it to be more than that. There are other scenarios where such properties may not hold.

Actually, other APIs, like streams, have a similar design but don’t intend to implement the Monad specification fully.

5. Conclusion

In this article, we looked at the concept of Monad, how they were introduced in Java, and the nuances of such implementation.

One can argue that what Java has is not actually a Monad implementation and that when designing for null safety, they broke the principles. However, many of the benefits of such a pattern are still there.

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)