Java
Collections
Sorting
Data Structures
Programming

Sorted collection in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Overview of Sorted Collection in Java

In Java, working with collections often involves maintaining order, whether it's natural or custom-defined. The Sorted Collection framework facilitates the storage, retrieval, and ordering of elements, making operations like searching and traversal more efficient. Key interfaces like SortedSet and SortedMap are fundamental to how sorted collections operate.

SortedSet Interface

SortedSet is a direct extension of the Set interface and ensures that elements stored within are sorted according to their natural ordering or a specified comparator. TreeSet is an integral implementation of SortedSet in Java.

Key Features of SortedSet:

  1. Ordering: Elements are stored in a sorted sequence.
  2. Null Elements: Supports null elements if the natural ordering allows null.
  3. Comparator: The default is the natural ordering, but a custom Comparator can be supplied.
  4. End Points: Provides methods to retrieve the first and last elements efficiently.

Example Usage:

java
1import java.util.SortedSet;
2import java.util.TreeSet;
3
4public class SortedSetExample {
5    public static void main(String[] args) {
6        SortedSet<Integer> set = new TreeSet<>();
7        set.add(10);
8        set.add(5);
9        set.add(2);
10
11        System.out.println("SortedSet: " + set);
12
13        // Access the first and last elements
14        System.out.println("First Element: " + set.first());
15        System.out.println("Last Element: " + set.last());
16    }
17}

SortedMap Interface

SortedMap interface, another vital part of the Java Collections Framework, extends the Map interface. It holds key-value pairs sorted based on the keys either by their natural order or according to a custom comparator provided at map creation time. TreeMap is one of the most common implementations.

Key Features of SortedMap:

  1. Sorting: Keys are sorted.
  2. Navigable Functions: Provides methods to get a view of a portion of the map whose keys are strictly less than a given key, or greater than, etc.
  3. Null Values: Permit null values but generally does not allow null keys (though, it's implementation dependent).

Example Usage:

java
1import java.util.SortedMap;
2import java.util.TreeMap;
3
4public class SortedMapExample {
5    public static void main(String[] args) {
6        SortedMap<String, Integer> map = new TreeMap<>();
7        map.put("Delta", 4);
8        map.put("Beta", 2);
9        map.put("Alpha", 1);
10
11        System.out.println("SortedMap: " + map);
12
13        // Access the first and last keys
14        System.out.println("First Key: " + map.firstKey());
15        System.out.println("Last Key: " + map.lastKey());
16    }
17}

Comparison between SortedSet and SortedMap

Sorted collections offer a way to manage ordered data efficiently, yet they cater to different needs. Below is a table summarizing key differences and features:

FeatureSortedSetSortedMap
Interface ExtendedSetMap
PurposeStore sorted unique elementsStore key-value pairs with sorted keys
Common ImplementationTreeSetTreeMap
Natural OrderingDefault for elementsDefault for keys
Custom ComparatorYesYes
Access Methodsfirst(), last()firstKey(), lastKey()

Additional Details and Considerations

  • Comparators: Implementing custom comparators allows flexibility beyond natural order, enabling sorting based on derived attributes or a particular sequence.
  • Performance: Both TreeSet and TreeMap have a time complexity of O(logn)O(\log n) for basic operations like add, remove, and search.
  • Thread Safety: By default, sorted collections are not synchronized. For concurrent access from multiple threads, you can use Collections.synchronizedSortedSet or Collections.synchronizedSortedMap.

Advanced Concepts

Java further enhances sorted collections with the NavigableSet and NavigableMap interfaces. These interfaces provide navigation methods such as:

  • floor(E e) - Finds greatest element less than or equal to a given element.
  • ceiling(E e) - Finds least element greater than or equal to a given element.
  • descendingSet() and descendingMap() - Provides a reverse order view of the set/map.

Example of NavigableSet:

java
1import java.util.NavigableSet;
2import java.util.TreeSet;
3
4public class NavigableSetExample {
5    public static void main(String[] args) {
6        NavigableSet<Integer> navSet = new TreeSet<>();
7        navSet.add(1);
8        navSet.add(2);
9        navSet.add(3);
10
11        System.out.println("Lower than 2: " + navSet.lower(2));
12        System.out.println("Higher than 2: " + navSet.higher(2));
13    }
14}

In conclusion, the Sorted Collections in Java provide robust and efficient tools to manage ordered data structures. Understanding their use and underlying mechanics is crucial for any Java developer aiming to write efficient, high-performance applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.