Spring Boot Iterator Pattern Example
By Ercan - 28/09/2025 - 0 comments
When working with multiple processing strategies—such as hashing algorithms—it is common to loop through a collection and apply each one. However, directly exposing the collection and iterating outside the component can make the code fragile and tightly coupled. This is where the Iterator Pattern comes into play.
The Use Case: Hashing Text with Multiple Algorithms
Our Spring Boot application takes a text input and returns the result of hashing that input with multiple algorithms:
- MD5
- SHA-1
- SHA-224
- SHA-256
- SHA-384
- SHA-512
Example Request:
curl --location 'http://localhost:8080/hash' \ --header 'Content-Type: application/json' \ --data '{ "text": "hello" }'
Example Response:
[ { "algorithm": "MD5", "hash": "5d41402abc4b2a76b9719d911017c592" }, { "algorithm": "SHA-1", "hash": "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d" }, { "algorithm": "SHA-224", "hash": "ea09ae9cc6768c50fcee903ed054556e5bfc8347..." } ]
The Core of the Pattern: HashIterator
The HashIterator
class is the central piece:
@Component @RequiredArgsConstructor public class HashIterator { private final List<HashIteration> hashIterations; public Map<HashType, String> hash(String text) { Map<HashType, String> result = new EnumMap<>(HashType.class); for (HashIteration hashIteration : hashIterations) { result.put(hashIteration.getHashType(), hashIteration.hash(text)); } return result; } }
Why is HashIterator so important?
- Encapsulation: Clients don’t need to know which algorithms exist or how they are applied.
- Sequential Access: Each
HashIteration
is applied in sequence without exposing the collection. - Extensibility: New algorithms can be added without modifying the
HashIterator
.
Benefits of Using the Iterator Pattern Here
- Clean abstraction – Clients simply call one method (
hash
) instead of managing loops. - Open/Closed Principle – Adding a new algorithm doesn’t require changing the iterator logic.
- Testability – Each
HashIteration
can be tested independently.
Conclusion
By introducing the Iterator Pattern into this Spring Boot application, we transformed a simple loop into a maintainable, extensible, and reusable structure. The HashIterator
class plays the critical role of hiding the iteration details and offering a clean interface for clients. This is a practical demonstration of how design patterns—when applied thoughtfully—can significantly improve the design and maintainability of everyday applications.
👉 You can explore the full source code on GitHub:
https://github.com/ercansormaz/iterator-pattern
Tags: spring boot, design pattern, iterator pattern, java