Course contentsShow
← Java
Lesson 974 of 2,87023. Collections Framework OverviewFree lesson

SortedSet and SortedMap: Ordered Collections

Learn how SortedSet and SortedMap maintain elements in sorted order, enabling range operations and ordering queries.

SortedSet and SortedMap: Ordered Collections

What you'll learn: How SortedSet and SortedMap maintain elements in sorted order and provide powerful range-based operations.

The Need for Sorted Collections

While Set and Map organize data efficiently, they don't guarantee any particular order. Sometimes you need collections that automatically keep elements sorted—like an alphabetized phone book or a leaderboard ranked by score. That's where SortedSet and SortedMap come in.

What Makes Them Special

SortedSet extends Set but maintains elements in ascending sorted order (according to their natural ordering or a custom comparator). SortedMap extends Map and keeps keys sorted.

Think of SortedSet like a bookshelf where books are always arranged alphabetically—no matter when you add them, they slot into the correct position automatically.

Key Capabilities

Both interfaces provide powerful ordering operations:

  • Range views: Get a subset of elements between two values
  • First/last access: Quickly retrieve the smallest or largest element/key
  • Ordering queries: Find elements before or after a specific value

For example, with a SortedSet of timestamps, you could instantly retrieve all entries from the past week without scanning every element. With a SortedMap of student names to grades, you could process students alphabetically or find everyone whose name falls between "A" and "M".

How They Maintain Order

The sorting happens automatically using either:

  • Natural ordering: For types like String or Integer that implement Comparable
  • Custom comparator: Your own sorting logic passed at creation

Unlike regular Set or Map, these sorted variants require elements/keys to be comparable—you can't sort what you can't compare!

Key Takeaway: SortedSet and SortedMap automatically maintain sorted order and enable efficient range-based queries, perfect when you need ordered data access.