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 – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

When we work with domain models in Java, we often deal with collections of entities fetched from databases, APIs, or in-memory structures. At some point, we almost always need to extract a list of IDs from these entities. It sounds simple, but the way we do it influences readability, performance, maintainability, and how easily other developers understand our code.

In this tutorial, we’ll explore different ways to collect IDs from a collection of entity objects. We’ll start with a simple entity, walk through progressively cleaner approaches.

2. Our Sample Entity

To keep things simple, we’ll use a basic User entity with an id field:

public class User {
    private final Long id;
    private final String name;

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

We are not using JPA annotations here since the focus is on Java collection processing. However, the same techniques also work for JPA entities.

3. The Classic Loop Approach

Most of us started our careers writing a simple loop to extract IDs. It’s readable, obvious, and works in all Java versions:

List<Long> extractIdsClassic(List<User> users) {
    List<Long> ids = new ArrayList<>();
    for (User user : users) {
        ids.add(user.getId());
    }
    return ids;
}

This approach feels familiar and works well when we want maximum clarity. But over time, we moved toward more expressive and concise solutions.

4. Using Java Streams

When we work with Java 8 and beyond, our code often becomes cleaner with streams. Streams let us express what we want rather than how to get it:

List<Long> extractIdsStream(List<User> users) {
    return users.stream().map(User::getId).collect(Collectors.toList());
}

This is more expressive and much easier to scan with our eyes. We immediately understand that we are mapping users to their IDs.

5. Using Set

In many real-world scenarios, IDs are unique by design. But sometimes we process external datasets that may contain duplicates. When that’s the case, returning a Set prevents logical errors downstream:

Set<Long> extractUniqueIds(List<User> users) {
    return users.stream().map(User::getId).collect(Collectors.toSet());
}

This makes intent very clear. If our IDs must be unique, using a Set communicates that decision.

6. Conclusion

In this article, it has become clear that extracting IDs from a collection of entities is more than just a routine task. It’s an opportunity to improve the clarity and consistency of our codebase. When we choose clean, expressive approaches, whether with simple loops or modern Java Streams, we make our intent obvious and reduce the chances of subtle bugs creeping in.

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.
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 – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW