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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’ll focus on the Cartesian product and how to get the Cartesian product of any number of sets in Java.

The Cartesian product of multiple sets is a useful concept in Java when you need to generate all possible permutations and combinations of elements from those sets. This operation is commonly used in various scenarios, such as test data generation, database queries, and game development.

2. Cartesian Product

A Cartesian Product is a mathematical operation that combines the elements of multiple sets to create a new set, where each element in the new set is an ordered tuple containing one element from each input set. The size of the Cartesian product is equal to the product of the sizes of the input set.

Let’s understand this with the help of an example by using three sets: setA, setB, and setC. We’ll calculate the Cartesian Product, and the resulting cartesianProduct set will contain all the ordered tuples representing the Cartesian Product of the three input sets:

public void cartesianProduct() {
    Set<Integer> setA = new HashSet<>(Arrays.asList(10,20));
    Set<String> setB = new HashSet<>(Arrays.asList("John","Jack"));
    Set<Character> setC = new HashSet<>(Arrays.asList('I','J'));
    
    Set<List<Object>> cartesianProduct = new HashSet<>();

    for (int i: setA) {
        for (String j: setB) {
            for (char k: setC) {
                List<Object> tuple = Arrays.asList(i,j,k);
                cartesianProduct.add(tuple);
            }
        }
    }
    
    for (List<Object> tuple: cartesianProduct) {
        System.Out.Println(tuple);
    }
}

Here is the output of the above program:

[10,John,I]
[10,John,J]
[10,Jack,I]
[10,Jack,J]
[20,John,I]
[20,John,J]
[20,Jack,I]
[20,Jack,J]

Now, let’s look at the various approaches to calculating the Cartesian product of any number of sets.

3. Get Cartesian Product using Plain Java

In the following sections, we’ll look at the various ways (iterative, recursive, and using Java8 streams) to generate the Cartesian Product.

3.1. Recursive Approach

We can use a recursive approach to compute the Cartesian Product of any number of sets in Java. The output is defined as List<List<Object>>, where each inner list can contain a mix of integers, strings, and characters. Here is a sample code to achieve this:

public static void main(String args[]) {
    List<List<Object>> sets = new ArrayList<>();
    sets.add(List.of(10, 20));
    sets.add(List.of("John", "Jack"));
    sets.add(List.of('I', 'J'));
    List<List<Object>> cartesianProduct = getCartesianProduct(sets);
    System.out.println(cartesianProduct);
}

public static List<List<Object>> getCartesianProduct(List<List<Object>> sets) {
    List<List<Object>> result = new ArrayList<>();
    getCartesianProductHelper(sets, 0, new ArrayList<>(), result);
    return result;
}

private static void getCartesianProductHelper(List<List<Object>> sets, int index, List<Object> current, List<List<Object>> result) {
    if (index == sets.size()) {
        result.add(new ArrayList<>(current));
        return;
    }
    List<Object> currentSet = sets.get(index);
    for (Object element: currentSet) {
        current.add(element);
        getCartesianProductHelper(sets, index+1, current, result);
        current.remove(current.size() - 1);
    }
}

The output contains eight elements in the list:

[[10,John,I]
[10,John,J]
[10,Jack,I]
[10,Jack,J]
[20,John,I]
[20,John,J]
[20,Jack,I]
[20,Jack,J]]

3.2. Iterative Approach Using Bit Manipulation

In the following code, we calculate the total number of possible combinations by using the bitwise shifting. The totalCombinations are computed as 2 to the power of the totalSets. The outer loop is crucial, iterating through all possible combinations using a binary counter i.

In the expression (((i >> j) & 1) == 1) we’re using a right shift operation that extracts the j-th bit of the binary representation of i. This bit helps us to determine whether we need to include the first or second element from the current set in the combination. If the extracted bit is set (or equals 1), the first element from the set is added to the combination; otherwise, the second element is included.

For example: ((i >> j) & 1) is equivalent to ((0b0010 >> 0) & 1), which results in 0b0010 & 0b00001, equal to 0b0000 or 0.

Therefore, the second element of Set 0 (sets.get(0).get(1)) is included in the combination.

These formed combinations are then accumulated within the result list and ultimately returned as Cartesian Product. Let’s take a look at another approach where we try to generate the Cartesian Product using bit manipulation:

public List<List<Object>> getCartesianProductIterative(List<List<Object>> sets) {
    List<List<Object>> result = new ArrayList<>();
    if (sets == null || sets.isEmpty()) {
        return result;
    }
    int totalSets = sets.size();
    int totalCombinations = 1 << totalSets;
    for (int i = 0; i < totalCombinations; i++) {
        List<Object> combination = new ArrayList<>();
        for (int j = 0; j < totalSets; j++) {
            if (((i >> j) & 1) == 1) {
                combination.add(sets.get(j).get(0));
            } else {
                combination.add(sets.get(j).get(1));
            }
        }
        result.add(combination);
    }
    return result;
}

Here is the output of the above program:

[20, Jack, J]
[10, Jack, J]
[20, John, J]
[10, John, J]
[20, Jack, I]
[10, Jack, I]
[20, John, I]
[10, John, I]

3.3. Using Streams

We’ll use Java 8 streams and recursive calls to generate the Cartesian Product. The cartesianProduct method will return a stream of all possible combinations. The base case is when the index reaches the size of the sets, and an empty list is returned to terminate the recursion. Let’s use streams to generate the Cartesian Product:

public List<List<Object>> getCartesianProductUsingStreams(List<List<Object>> sets) {
    return cartesianProduct(sets,0).collect(Collectors.toList());
}

public Stream<List<Object>> cartesianProduct(List<List<Object>> sets, int index) {
    if (index == sets.size()) {
        List<Object> emptyList = new ArrayList<>();
        return Stream.of(emptyList);
    }
    List<Object> currentSet = sets.get(index);
    return currentSet.stream().flatMap(element -> cartesianProduct(sets, index+1)
      .map(list -> {
          List<Object> newList = new ArrayList<>(list);
          newList.add(0, element);
          return newList;
      }));
}

Here is the output of the above program:

[10,John,I]
[10,John,J]
[10,Jack,I]
[10,Jack,J]
[20,John,I]
[20,John,J]
[20,Jack,I]
[20,Jack,J]

4. Get Cartesian Product using Guava

Guava, which is a popular library developed by Google, provides utilities to work with collections, including computing the Cartesian Product of multiple sets. To use Guava for computing the Cartesian Product, let’s start by adding Google’s Guava library dependency in pom.xml:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version>
</dependency>

The latest version of the dependency can be checked here.

Now, we’ll use Guava’s Set.cartesianProduct() method, which takes a list of sets List<Set<Object>> as an input and returns a set of lists Set<List<Object>> containing all the combinations of elements from the input sets. Finally, we transformed the set of lists into a list of lists and returned the output:

public List<List<Object>> getCartesianProductUsingGuava(List<Set<Object>> sets) {
    Set<List<Object>> cartesianProduct = Sets.cartesianProduct(sets);
    List<List<Object>> cartesianList = new ArrayList<>(cartesianProduct);
    return cartesianList;
}

The output contains eight elements in the list:

[[10,John,I]
[10,John,J]
[10,Jack,I]
[10,Jack,J]
[20,John,I]
[20,John,J]
[20,Jack,I]
[20,Jack,J]]

5. Conclusion

In this article, we focused on various ways to calculate the Cartesian Product of any number of sets in Java.

While some of them were purely Java, others required additional libraries. Each method has its advantages, and users may prefer them based on the specific use case and performance requirements. The recursive approach is straightforward and easier to understand, while the iterative approach is generally more efficient for larger sets.

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.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments