Menu

1 / 3

From O(n ) to O(n): Replace Nested Loops with a HashMap in Java

DEV Community: java·Moises Gamio·19 days ago
#Bej0r6NH
#devtojava#devto#dev#address#order
Reading 0:00
15s threshold

One endpoint in a B2B order system I worked on returned 1,000 orders, and it was slow. The database wasn't the problem. Two innocent-looking nested loops were. Here's how one data structure, the HashMap, turned 2,000,000 comparisons into about 3,000.

A List data structure is an ordered collection of items, where each item has a specific position or index within the list.

A HashMap is a data structure that stores key-value pairs, enabling efficient retrieval of values based on their keys. It uses a hash function to determine the storage location (or "bucket") of each key-value pair within an underlying array, allowing for fast lookups, insertions, and deletions.

Use Case

We have a RESTful API endpoint to retrieve a list of orders placed by a given buyer.

The response includes different kinds of addresses per order, as you can see in the following schema:

[ { "orderId" : 123456 , "buyerId" : 1234 , "customerNumberId" : 12 , "supplierId" : 1 , "orderDate" : "2025-05-15" , "orderDeliveryAddress" : {…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.