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 explore how to filter a list that contains nested lists in Java. When working with complex data structures, such as lists of objects that contain other lists, it becomes essential to extract specific information based on certain criteria.

2. Understanding the Problem

We’ll work with a simple example where we have a User class and an Order class. The User class has a name and a list of Orders, while the Order class has a product and a price. Our goal is to filter a list of users based on some conditions applied to their nested orders.

Below is how our data model is structured:

class User {
    private String name;
    private List<Order> orders;
    
    public User(String name, List<Order> orders) {
        this.name = name;
        this.orders = orders;
    }

    // set get methods
}

class Order {
    private String product;
    private double price;
    
    public Order(String product, double price) {
        this.product = product;
        this.price = price;
    }

    // set get methods
}

In this setup, each User can have multiple Order objects, which provide the details necessary for us to filter the users based on certain criteria related to their orders, such as price.

To demonstrate the filtering logic, we’ll first create some sample test data. In the example below, we prepare two Order objects and associate them with three User objects:

Order order1 = new Order("Laptop", 600.0);
Order order2 = new Order("Phone", 300.0);
Order order3 = new Order("Monitor", 510.0);
Order order4 = new Order("Monitor", 200.0);

User user1 = new User("Alice", Arrays.asList(order1, order4));
User user2 = new User("Bob", Arrays.asList(order3));
User user3 = new User("Mity", Arrays.asList(order2));

List users = Arrays.asList(user1, user2, user3);

Suppose we want to find all users who have placed orders with a price greater than $500. In this case, we’d expect our filtering logic to return two users, as Alice and Bob both have an order meeting this criterion.

3. Traditional Looping Approach

Before Java 8 introduced the Stream API, the typical way to filter lists was by using traditional for loops. Let’s take the same example and implement filtering using nested for loops:

double priceThreshold = 500.0;

List<User> filteredUsers = new ArrayList<>();
for (User user : users) {
    for (Order order : user.getOrders()) {
        if (order.getPrice() > priceThreshold) {
            filteredUsers.add(user);
            break;
        }
    }
}

assertEquals(2, filteredUsers.size());

In this approach, we loop through each User and then loop through their list of Orders. As soon as we find an order that matches our condition, we add the user to the filtered list and exit the inner loop with a break.

This approach works fine and is easy to understand, but it requires manual management of the nested loops. It also lacks the functional programming style that streams provide.

4. Filtering Using Java Streams

With Java 8, we can use Streams for cleaner code. Let’s use this approach to solve the same problem as before: We want to filter out the users who have placed an order with a price of more than $500. We can do this by using Java Streams to check each user’s list of orders to see if it contains an order meeting our condition:

double priceThreshold = 500.0;

List<User> filteredUsers = users.stream()
  .filter(user -> user.getOrders().stream()
    .anyMatch(order -> order.getPrice() > priceThreshold))
  .collect(Collectors.toList());

assertEquals(2, filteredUsers.size());

In this code, we’re streaming through the list of Users and then, for each user, we’re checking if any of their orders have a product price of more than $500. The anyMatch() method helps us check if at least one of the user’s orders had paid more than $500.

5. Filtering With Multiple Conditions

Now, suppose we want to filter users who ordered a “Laptop” and also paid more than $500. In this case, we can combine conditions inside the anyMatch() method:

double priceThreshold = 500.0;
String productToFilter = "Laptop";

List<User> filteredUsers = users.stream()
  .filter(user -> user.getOrders().stream()
    .anyMatch(order -> order.getProduct().equals(productToFilter) 
      && order.getPrice() > priceThreshold))
  .collect(Collectors.toList());

assertEquals(1, filteredUsers.size());
assertEquals("Alice", filteredUsers.get(0).getName());

Here, we expect that only user1 will be included in the filteredUsers list, as Alice is the only user who has ordered a “Laptop” and paid more than $500.

6. Using a Custom Predicate

Another approach is to encapsulate our filtering logic in a custom Predicate. This allows for more readable and reusable code. Let’s define a Predicate that checks whether a user’s order matches our condition:

Predicate<User> hasExpensiveOrder = user -> user.getOrders().stream()
  .anyMatch(order -> order.getPrice() > priceThreshold);

List<User> filteredUsers = users.stream()
  .filter(hasExpensiveOrder)
  .collect(Collectors.toList());

assertEquals(2, filteredUsers.size());

This method improves readability by keeping the filtering logic isolated, and the predicate can be reused for other filtering operations if needed.

7. Filtering While Preserving Structure

Let’s consider the scenario where we want to keep all users on the list but only include orders that meet a certain condition. Instead of removing users without valid orders, we’re modifying their list of orders and filtering out only the orders that don’t meet the condition.

In this case, we need to modify the user’s list of orders while preserving the rest of the user object:

List<User> filteredUsersWithLimitedOrders = users.stream()
  .map(user -> {
    List<Order> filteredOrders = user.getOrders().stream()
      .filter(order -> order.getPrice() > priceThreshold)
      .collect(Collectors.toList());
    user.setOrders(filteredOrders);
    return user;
  })
  .filter(user -> !user.getOrders().isEmpty())
  .collect(Collectors.toList());

assertEquals(2, filteredUsersWithLimitedOrders.size());
assertEquals(1, filteredUsersWithLimitedOrders.get(0).getOrders().size());
assertEquals(1, filteredUsersWithLimitedOrders.get(1).getOrders().size());

Here, we’re using map() to modify each User object. For every user, we filter their list of orders to include only those that meet the price condition, and then, we update their order list with the filtered results.

8. Using flatMap()

Instead of using nested streams, we can leverage the flatMap() method to flatten the nested lists and process the items as a single stream. This approach simplifies filtering across nested lists by avoiding multiple stream() calls.

Let’s see how we can use flatMap() to filter User objects based on their Order list:

List<User> filteredUsers = users.stream()
  .flatMap(user -> user.getOrders().stream()
    .filter(order -> order.getPrice() > priceThreshold)
    .map(order -> user)) 
  .distinct()
  .collect(Collectors.toList());

assertEquals(2, filteredUsers.size());

In this approach, we use the flatMap() method to transform each User into a stream of their associated Order objects. By doing so, we can process all orders as a single unified stream.

9. Handling Edge Cases

There may be cases where some users have no orders at all. To prevent potential NullPointerExceptions when handling users without any orders, we should implement checks to ensure that the orders are not null or empty:

User user1 = new User("Alice", Arrays.asList(order1, order2));
User user2 = new User("Bob", Arrays.asList(order3))
User user3 = new User("Charlie", new ArrayList<>());
List users = Arrays.asList(user1, user2, user3);

List<User> filteredUsers = users.stream()
  .filter(user -> user.getOrders() != null && !user.getOrders().isEmpty()) 
  .filter(user -> user.getOrders().stream()
    .anyMatch(order -> order.getPrice() > priceThreshold))
  .collect(Collectors.toList());

assertEquals(2, filteredUsers.size());

In this example, we’re first checking if the orders list is not null and not empty before applying further filters. This makes our code safer and avoids runtime errors.

10. Conclusion

In this article, we learned how to filter a list based on their nested lists in Java. We explored traditional loops, Java Streams, custom predicates, and how to handle edge cases. By using Streams, we can write cleaner and more efficient code.

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)