eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

Java provides a rich collection framework with various interfaces and classes that cater to diverse data structure needs. However, it doesn’t provide a built-in implementation of sorted lists. In this article, we look into the reasons behind this absence, comparing the concepts of sorting on insertion and sorting on demand.

We also discuss how sorting on insertion can potentially break the contract of the List interface, and we explore alternative ways to achieve sorted behavior.

2. Sorting on Insertion and Sorting on Demand

To understand why sorted lists aren’t present in Java, we must first differentiate between sorting on insertion and sorting on demand.

2.1. Sorting on Insertion

Sorting on insertion involves rearranging elements immediately at the time of insertion, ensuring a sorted order with each addition. Some data structures do behave this way. Usually, their implementation is based on a tree structure, most notably, TreeSet and TreeMap.

The main advantage of a sorting-on-insertion implementation is the efficiency of reading data from such a structure. Writing data is more costly because we need to find the right place in the structure and, sometimes, even rearrange existing data.

This cost may be much smaller than that of sorting the whole unsorted collection on every read. However, sorting on insertion with multiple sorting conditions is much more complex and involves keeping track of multiple index tree structures, making saving even more complex and costly.

2.2. Sorting on Demand

On the other hand, sorting on demand defers the sorting operation until explicitly requested by the user. Sorted reads are costly because we must sort the whole collection every time.

On the upside, saving data is very cheap, and the underlying data structure can be much simpler — for example, an array backing the ArrayList. Moreover, we can decide to sort by different conditions each time or even not to sort at all.

3. Why Sorting on Insertion Breaks the List Contract

Sorting on insertion would break the contract of the List interface. The contract of the List interface specifies that elements should be maintained in the order they were inserted, allowing for duplicates. Sorting on insertion would violate this contract by rearranging the elements. This order is important for many list operations and algorithms that rely on the order of elements.

By sorting the list on every insertion, we’d change the order of elements and potentially disrupt the expected behavior of other methods defined in the List interface.

4. Implementing Sorting on Insertion

In most cases, we shouldn’t implement our own data structures to achieve sorting on insertion. There are already collections that do it well, although they’re based on tree data structure, not linear lists.

4.1. Using TreeSet With Natural Order

If we’re happy with the natural order and want to ignore duplicates, we can create a TreeSet instance with a default constructor:

TreeSet<Integer> sortedSet = new TreeSet<>();
sortedSet.add(5);
sortedSet.add(2);
sortedSet.add(8);
sortedSet.add(1);
System.out.println(sortedSet); // Output: [1, 2, 5, 8]

4.2. Using TreeSet With a Custom Order

We can also use a custom Comparator to achieve the custom order. Let’s say we have a set of strings, and we want to sort them by their last letter:

Comparator<String> customComparator = Comparator.comparing(str -> str.charAt(str.length() - 1));

TreeSet<String> sortedSet = new TreeSet<>(customComparator);

sortedSet.add("Canada");
sortedSet.add("Germany");
sortedSet.add("Japan");
sortedSet.add("Sweden");
sortedSet.add("India");
System.out.println(sortedSet); // Output: [India, Canada, Sweden, Japan, Germany]

5. Implementing Sorting on Demand

If we want to use the List interface, we can implement sorting on demand. We can do that in two ways: by sorting in place or by creating a new sorted list.

5.1. Sorting in Place

To sort a list in place, we’ll use the sort method from the Collections class. It’ll mutate our list, changing the order of the elements:

List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
System.out.println("Before sorting: " + numbers); // Output: Before sorting: [5, 2, 8, 1]

Collections.sort(numbers);
System.out.println("After sorting: " + numbers); // Output: After sorting: [1, 2, 5, 8]

Sorting in place is usually faster and more memory-efficient, but by definition, it needs to work on a mutable collection, which isn’t always desirable or possible.

5.2. Sorting Without Mutation

We can also sort our list without changing the original collection. To do that, we’ll create a stream from the list, sort it, and then collect it into a new list:

List<Integer> sortedList = numbers.stream().sorted().collect(Collectors.toList());

System.out.println("After sorting: " + sortedList); // Output: After sorting: [1, 2, 5, 8]
System.out.println("Original list: " + numbers); // Output: Original list: [5, 2, 8, 1]

We could also use the knowledge from previous paragraphs, and instead of collecting the elements of the stream to a new list, we could collect it to a TreeSet. That way, we wouldn’t need to explicitly sort it — the TreeSet implementation will do that for us:

TreeSet<Integer> sortedSet = numbers.stream().collect(Collectors.toCollection(() -> new TreeSet<>()));

System.out.println("After sorting: " + sortedSet); // Output: After sorting: [1, 2, 5, 8]
System.out.println("Original list: " + numbers); // Output: Original list: [5, 2, 8, 1]

6. Summary

In this article, we’ve seen that the absence of a built-in sorted list implementation in Java’s collection framework is a thoughtful decision that upholds the List interface contract. We then looked into which data structures we can use instead if we want to achieve sorting on insertion.

Finally, we also learned how to sort on demand if we decide to use the List interface.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

eBook Jackson – NPI EA – 3 (cat = Jackson)