Sortedset
SortedSet¶
Picture a self-arranging bookshelf 📚
No matter how you toss books in, they line up neatly by title or number. That quiet librarian is SortedSet.
🧠 What is SortedSet?¶
SortedSet is part of the Java Collections Framework
```java id="v1g4zp"
SortedSet👉 It is a **Set that maintains elements in sorted order**
---
## 🔑 Key Characteristics
* ❌ No duplicate elements
* ✔ Elements are **always sorted**
* ❌ No index-based access
* ❌ Null not allowed (in most implementations like `TreeSet`)
* Sorting based on:
* Natural order (`Comparable`)
* OR custom `Comparator`
---
## 🏗️ Implementation
### ✔ TreeSet (Primary Implementation)





```java id="6n3o4z"
SortedSet<Integer> set = new TreeSet<>();
- Uses Red-Black Tree
- Time complexity → O(log n)
⚙️ Important Methods¶
🔹 Basic Methods¶
```java id="ntg2ru" set.add(10); set.add(5); set.add(20);
---
### 🔹 SortedSet Specific Methods
```java id="8w3w0d"
set.first(); // smallest element
set.last(); // largest element
set.headSet(15); // elements < 15
set.tailSet(10); // elements >= 10
set.subSet(5, 20); // range [5, 20)
🧠 Example¶
```java id="d4v0kc"
SortedSet
set.add(30); set.add(10); set.add(20);
System.out.println(set);
✔ Automatically sorted ✔ No duplicates
🔄 Custom Sorting¶
```java id="u5h5zx"
SortedSet
set.add("A"); set.add("C"); set.add("B");
System.out.println(set);
⚔️ SortedSet vs Set¶
| Feature | SortedSet 🌿 | Set |
|---|---|---|
| Order | Sorted | No guarantee |
| Duplicates | Not allowed | Not allowed |
| Extra methods | Yes | No |
🎯 Interview Nuggets¶
SortedSetis an interface-
Implemented by:
TreeSet-
Extended by:
-
NavigableSet(adds more navigation methods) - Elements must be comparable or use comparator
🧠 Memory Trick¶
SortedSet = Set + Always Sorted 🌿