SortedSet-and-TreeSet-in-Java
SortedSet-and-TreeSet-in-Java
Presented by:
3)Md.Faiz 23019215200111
Core Package
It is an integral part of the java.util package, providing essential
utility classes.
Key Interfaces
Important interfaces include List, Set, Map, and the specialized
SortedSet for ordered data.
Today's Focus
This presentation will focus on the SortedSet interface and its
concrete implementation, TreeSet.
What is a Set?
No Duplicates
A Set ensures that all elements stored within it are unique,
preventing any duplicate entries.
Unordered Elements
By default, Set implementations do not maintain any
specific order for their elements.
Key Implementations
Common implementations include HashSet, LinkedHashSet,
and the ordered TreeSet.
Introduction to SortedSet
Interface Definition
SortedSet is a crucial interface in Java, extending the base Set interface.
Ordered Elements
It ensures that all elements are maintained in a specific sorted order,
either natural or custom.
Sorting Mechanism
Elements are sorted based on their natural ordering or by a user-defined
Comparator.
Key Methods
It provides methods like first(), last(), headSet(), tailSet(), subSet(), and
comparator().
TreeSet – SortedSet Implementation
Class Implementation Internal Structure Guaranteed Properties Performance
TreeSet is a concrete It utilizes a self-balancing TreeSet ensures that all Operations like add,
class that fully Red-Black Tree data elements are unique and remove, and contains
implements the structure to store maintained in a sorted have a time complexity
SortedSet interface. elements efficiently. order. of O(log n).
TreeSet Syntax Example
import java.util.*;
public class Example {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(10);
set.add(5);
set.add(20);
System.out.println(set); // [5, 10, 20]
}
}
• Automatically sorted
• No duplicates allowed
TreeSet with Custom Comparator
You can define custom sorting logic.
Encapsulation Polymorphism
The intricate internal Red-Black The SortedSet interface can
Tree logic is completely hidden reference a TreeSet object,
from the user. showing flexible type usage.
Use Cases of TreeSet
Sorted Data Storage
Ideal for maintaining elements in a consistently sorted order.
Duplicate Removal
Efficiently removes duplicates while preserving the
collection's order.
Priority Systems
Useful for implementing systems based on element
priority or ranking.
Unique Identifiers
Perfect for storing unique identifiers like usernames
or leaderboard scores.
Advantages & Limitations
Advantages Limitations