undo
Go Beyond the Code
arrow_forward_ios

The Data Structures Behind Your Stack

Angel Tomas Concha Layme
Software Engineer & Solver
December 4, 2026
To learn more about this topic, click here.

Discover how Java data structures boost Spring Boot performance, memory use, and design.

At first, web development can give the impression that frameworks and libraries hide everything that really matters. But as systems grow, with more traffic, background jobs, and integrations, decisions about data structures start becoming visible in performance, clarity, and correctness. This article shares real-world patterns where classic data structures appear implicitly, how to recognize them, and how having studied them before makes these solutions feel more intuitive. The goal is to help junior developers gain confidence: the fundamentals are not "academic," they are leverage.


1. Introduction

When was the last time you used a data structure?Β 

If you answered "in a coding interview" or "in university," look at the last controller you wrote. That List<Order> returned by your repository? It's an array. The .stream().filter().map().toList() pipeline? That's array processing. The @Cacheable on your service? That's a hash map. You've been using them every day.

This article walks through six data structures, from the simplest to the most advanced, and shows where they appear in real Java/Spring Boot applications. Not as interview exercises. Not as textbook theory. But as patterns that already exist in the code you write and the tools you use, often without you noticing.

The goal: the next time you see one of these structures disguised as a framework, you'll recognize it. Because the fundamentals are not "academic," they are leverage.

We'll cover six structures organized by increasing complexity: from the most familiar (List, Map) to the ones that seem more "textbook" but turn out to be everywhere (Trie, Graph). For each one, the pattern is the same: a real problem, Java/Spring Boot code, and the moment where it's revealed that the data structure was always there.


2. Array / List: The one you use every day

There's an endpoint you've probably written dozens of times: receive a request, query the database, transform the results, return them. Filter, map, sort, paginate. It's so routine that it doesn't feel like a data structure decision. But it is.

A List is a decision: you chose order over uniqueness, sequence over association. And every operation you perform on it (filtering before or after sorting, materializing in memory or delegating to the DB, loading everything or paginating) has real implications.

Look at this controller:



            

‍

It works. It's readable. But there's a problem: findAll() loads all products into memory. If you have 50 thousand products, you've just put 50 thousand objects into an ArrayList only to return 20.

Now look at the same operation delegated to the database:



            


The database handles the filter, the sort, and the pagination. The Page<T> returned by Spring Data is a List<T> wrapped with pagination metadata. It only loads the 20 records you need.Β 

The difference between both approaches is understanding that a list has a size, and size has a cost. Every findAll() is a memory decision in disguise.

There's a detail many overlook: operation order matters. Filtering before sorting reduces N, and sorting N items costs O(N log N). If you filter after, you're paying the sort on data you're going to discard. The Stream API didn't invent pipelines; it made list operations composable. And pagination? It's simply arguing about how big your list should be.

It's also worth noting the difference between Page<T> and Slice<T> in Spring Data. Page executes an additional COUNT query to know the total number of records. Slice only tells you if there's a next page. For a "load more" UI, Slice is cheaper. For pagination with page numbers, you need Page. Both wrap a List; the decision is how much metadata you want about that list.

Spring Batch takes this idea even further: its chunk-oriented processing reads data into a List of configurable size (chunk(100, transactionManager)), processes it, and writes it. The list IS the chunk. The chunk size is your memory budget per iteration.

‍Lists hold data. Maps help you find it.


3. Hash Map: The N+1 Killer

You have a list of orders and need to attach the customer name to each one. The naive approach: for each order, query the customer.



            


If you have 200 orders, that's 201 queries to the database. The fix? A HashMap:



            


Two queries total. The key line is Collectors.toMap(Customer::getId, Function.identity()), which builds a HashMap<Long, Customer> with O(1) per lookup. The N+1 disappears because it's now O(n + m) instead of O(n Γ— m).

This pattern (batch fetch + index by ID) is probably the single most impactful performance optimization for Spring Data applications. It turns N+1 into 2 queries. And it's composable: you can do the same with Collectors.groupingBy() to build a Map<Long, List<Payment>> that groups payments by invoice, or a Map<String, List<Event>> that groups events by type. A single pass, O(n), and you have a multi-value index ready to use.

Deduplication follows the same logic. If you receive duplicate webhooks (at-least-once guarantee), putIfAbsent on a LinkedHashMap or a HashSet gives you dedup in O(1) per element. A HashSet is literally a HashMap where the values don't matter. Deduplication is not a library feature, it's a data structure.

And the best part: you already use hash maps without knowing it. Every time you write @Cacheable:



            

Spring puts a hash map between your service and the database. Caffeine, the standard Spring Boot cache, is a ConcurrentHashMap with eviction policies. @Cacheable is Spring's way of saying "put a hash map here."

Every cache is a map. Every map is a decision about what to remember.

‍Maps help you find things. Queues help you defer them.

‍
4. Queue: Process this later

A user signs up. Your endpoint needs to create the user, send a welcome email, notify analytics, and trigger a webhook to the CRM. The last three are slow, unreliable, and non-essential for the immediate response.

The solution: enqueue them.



            


It looks simple. But what happens underneath is this: @Async sends each call to a ThreadPoolTaskExecutor, which internally has a LinkedBlockingQueue. The request thread returns immediately. The queue is the buffer between your request and the workers.

This works, but it has a limitation: if the application restarts, queued tasks are lost. For production, the same idea is externalized with RabbitMQ:



            


RabbitMQ keeps the queue durable. If the app restarts, unprocessed messages are still there. If a message fails repeatedly, it goes to a dead letter queue (DLQ) instead of blocking the flow.

The word "later" in your architecture is a queue. @Async is a thread pool with a queue inside. RabbitMQ is a queue with an application around it. Both are the same data structure; the difference is where it lives and what guarantees you need.

An interesting detail on the RabbitMQ side: you can build a structured retry mechanism using only queues. If a message fails, you send it to a "retry queue" with a 30-second TTL. When the TTL expires, RabbitMQ routes it back to the main queue (using dead letter routing). If it fails three times, it goes to a final DLQ for manual inspection. The entire retry loop is built with queue semantics: TTL + dead letter routing. It's not a retry system, it's queues routing messages to other queues.

Every @Async method you write is a bet that the work will finish before the application restarts. If you don't like that bet, you need a queue that survives restarts.

‍But what if "later" isn't enough, if you need "the most urgent one first"?


5. Priority Queue / Heap: Most urgent first

Your system sends webhooks to external partners. Each webhook has a deadline ("deliver within 30 minutes at most") and a retry schedule ("if it fails, retry at 5s, 15s, 60s, 300s"). You have hundreds of pending webhooks in different retry states.



            


The worker is simple: take from the queue, try to deliver, and if it fails, re-enqueue with the next retry time:



            


DelayQueue automatically blocks until the soonest element is ready. No polling every second checking all items. No sorting the entire list. The heap internally keeps the minimum at the front in O(log n).

And the most interesting part: you already use this concept without knowing it. Every time you write scheduler.schedule(task, 5, MINUTES), you're inserting into a heap. ScheduledExecutorService internally uses a DelayedWorkQueue, which is a priority queue. Quartz does the same with its triggers.

The difference between "check everything every second" and "wake up exactly when needed" is a priority queue. A DelayQueue is a priority queue wearing a watch.

If you need this at scale with durability, you can implement the same pattern with a database table: SELECT * FROM pending_retries WHERE next_attempt_at <= NOW() ORDER BY next_attempt_at LIMIT 10. The ORDER BY is the database performing the heap extraction for you. It's slower (polling every N seconds) but survives restarts and works across multiple instances.

‍Heaps order by priority. Tries order by prefix.


6. Trie: Every search box, every route

Type three letters in a search box. In milliseconds, suggestions appear. How does this work with millions of terms?

The answer is a trie: a tree where each node is a character, and paths from the root spell out words. To find everything that starts with "pro," you just traverse the path p β†’ r β†’ o and collect everything below it. Here's the minimal implementation:



            


About 40 lines. Load it with products at startup, and every prefix search returns results in microseconds, regardless of how many products you have.

In production, Elasticsearch does the same at scale with its completion suggester. The difference is that instead of an in-memory trie, it uses an FST (finite state transducer), essentially a compressed, immutable trie. When you configure @CompletionField in Spring Data Elasticsearch, you're telling Elasticsearch "build a trie for this field."

But there's another trie you use every day without noticing: Spring MVC's router. When you define @GetMapping("/api/users/{id}/orders"), Spring MVC parses the URL segments into a tree (api β†’ users β†’ {id} β†’ orders) and each request is resolved by traversing that tree segment by segment. The PathPatternParser, the default since Spring Boot 2.6, is a routing trie. Every @GetMapping you write adds a node.

The trie's prefix search operation is O(m + k) where m is the prefix length and k the number of results, independent of the total dictionary size. A trie with 10 million entries finds all words starting with "pro" just as fast as one with 100.

Need a trie for production? You don't have to implement it yourself. Apache Commons Collections has PatriciaTrie (a radix trie that compresses single-child node chains), and if you need real scale, Elasticsearch is the standard. But understanding that a trie is underneath lets you make better decisions: why data must be indexed beforehand, why weight affects ranking, and why the suggestion is so fast.

The trie is the data structure of "starts with...", and you use it every time you type in a search box or make an HTTP request.

‍Tries organize hierarchical keys. Graphs organize everything else.

‍
7. Graph: The shape of your system

A data pipeline has tasks that depend on each other:

cleanData and enrichData can run in parallel. But mergeData has to wait for both. How do you determine the correct order? This is a DAG (directed acyclic graph), and it's solved with topological sort:



            


Each group in braces can execute in parallel. The topological sort guarantees that no task runs before its dependencies.

Sound familiar? It should. This is exactly what Spring does when it starts your application.

When you define beans with @Service, @Component, @Autowired, Spring builds a dependency graph: Bean A depends on Bean B depends on Bean C. Then it performs a topological sort to determine the creation order. And when you see BeanCurrentlyInCreationException? That's Spring telling you it found a cycle in that graph, a circular dependency that makes ordering impossible.

This same algorithm shows up in more places than you might expect:

If you need graph algorithms in production (cycle detection, shortest path, impact analysis), JGraphT is the standard library for Java. But most of the time, a simple Map<String, Set<String>> as an adjacency list is enough, like the TaskDag we just built.


8. Conclusion: Data structures never left

We've traveled a path from the most familiar to the most unexpected. From a findAll() that returns a list, to a BeanCurrentlyInCreationException that hides a graph. The pattern repeats in every section: there's a data structure behind something you already use, and recognizing it gives you an advantage you didn't have before.

Structure Where it hides What you can now recognize
List Page<T>, Spring Batch chunks, Stream pipelines Every findAll() is a memory decision
Map @Cacheable, Collectors.toMap(), Caffeine Your cache is a hash map; your N+1 fix is too
Queue @Async, RabbitMQ, ThreadPoolTaskExecutor "Later" in your architecture means a queue
Priority Queue DelayQueue, ScheduledExecutorService, Quartz When the order isn't FIFO, there's a heap
Trie Elasticsearch completion, Spring MVC PathPatternParser Your search box and your router are tries
Graph Spring DI, Maven, CI/CD pipelines, @ManyToMany BeanCurrentlyInCreationException = cycle in a graph


You don't need to implement these structures from scratch. Most of the time, the framework already does it for you. The value isn't in the code, it's in the recognition.

When you understand that @Cacheable is a hash map, you can reason about how much memory it consumes, when it invalidates, and why a cache hit is nanoseconds but a miss can be milliseconds. When you understand that @Async is a queue with a LinkedBlockingQueue inside, you can decide whether you need one that survives restarts or one that runs in-process. When you understand that a DelayQueue is a heap ordered by time, you can stop polling every second and let the structure do the work. And when you understand that your bean dependencies are a graph, the circular dependency error stops being cryptic: it's cycle detection doing its job.

This recognition matters especially when things go wrong. A slow endpoint loading 100K rows? List problem, paginate. A service with N+1 queries? Map problem, index. Tasks executing out of order? Graph problem, do a topological sort. Being able to name the problem is the first step toward solving it.

The fundamentals are not academic, they are leverage. The difference between a junior developer who "uses frameworks" and one who understands why they work is, more often than not, recognizing the data structure the framework hides.

Next time you see @Cacheable, think "hash map." Next time you see @Async, think "queue." Next time you see BeanCurrentlyInCreationException, think "cycle in a graph."

‍Data structures never left. They just disguised themselves as frameworks.

Angel Tomas Concha Layme
Software Engineer & Solver
Arrow icon go to top

Start Your Digital Journey Now!

Which capabilities are you interested in?
You may select more than one.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.