Let's get started with a Microservice Architecture with Spring Cloud:
Finding the Collection of All IDs in a Collection of Entities
Last updated: December 15, 2025
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.
As always, the code presented in this article is available over on GitHub.















