☕↕️ SORTED 🤜 versus 🤛 ORDERED in Java: know the DIFFERENCE
A collection can be ordered without being sorted. Here’s why 👇
🔸 TLDR
▪️ Ordered means elements have a predictable encounter order.
▪️ Sorted means elements follow a sorting rule: natural order or a Comparator.
▪️ Every sorted structure has an order, but an ordered structure is not necessarily sorted.
🔸 1️⃣ ORDERED: INSERTION ORDER
Output:
[Bruno, Ken, Frank, Vlad]
List preserves its element order. But "Bruno", "Ken", "Frank", "Vlad" is not alphabetically sorted.
🔸 2️⃣ SORTED: NATURAL ORDER
Output:
[Bruno, Frank, Ken, Vlad]
sort(null) uses the elements' natural ordering. The list was already ordered; sorting changes that order according to a rule.
🔸 3️⃣ ORDERED SET ≠ SORTED SET
Iteration gives:
Bruno, Ken, Frank, Vlad
LinkedHashSet preserves insertion order. It is therefore ordered, but it does not automatically sort its elements.
🔸 4️⃣ SORTED SET
Iteration gives:
Bruno, Frank, Ken, Vlad
TreeSet maintains elements according to their natural ordering or a supplied Comparator.
🔸 5️⃣ STREAM ORDER AND SORTING
Output:
Bruno
Frank
Ken
Vlad
Stream.sorted() explicitly imposes a sorted encounter order.
Without sorted(), a stream may still have an encounter order inherited from its source.
🔸 TAKEAWAYS
▪️ Ordered = where elements appear relative to each other.
▪️ Sorted = why they appear in that order.
▪️ List → ordered.
▪️ LinkedHashSet → insertion-ordered.
▪️ TreeSet → sorted.
▪️ HashSet → no defined encounter order.
▪️ Stream.sorted() → explicitly sorts the stream.
Same word family. Very different contract. ☕
#Java #JavaDevelopment #JavaCollections #JavaStreams #Programming #SoftwareEngineering #JavaCertification #OCP
Go further with Java certification:
Java👇
Spring👇
SpringBook👇
JavaFullstackBook👇