
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create TreeSet with Custom Comparator in Java
In this article, we will learn to create a TreeSet with a custom Comparator in Java. TreeSet is a set that stores elements in sorted order. By default, elements are sorted in natural ordering (numbers in ascending order).
Understanding TreeSet and Comparators
Following are some key points for TressSet and Comparators ?
- A TreeSet is a part of the Java Collections Framework and implements the NavigableSet interface.
- It automatically sorts elements as they are added.
- By default, it sorts elements using their natural ordering (determined by the Comparable interface).
- To define a custom sorting order, we use the Comparator interface.
Creating a TreeSet with a Custom Comparator
To create a TreeSet with a custom comparator, let us first create an Integer array and set it to TreeSet ?
Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
Using the Comparator with reverseOrder(), which returns a comparator that imposes the reverse of the natural ordering ?
Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
Adding elements from the array to TreeSet using for loop and add() method ?
for (int i = 0, n = arr.length; i < n; i++) { set.add(arr[i]); }
Example
Below is an example of creating a TreeSet with a custom Comparator in Java ?
import java.util.Collections; import java.util.Set; import java.util.TreeSet; public class Demo { public static void main(String args[]) throws Exception { Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder()); for (int i = 0, n = arr.length; i < n; i++) { set.add(arr[i]); } System.out.println("TreeSet = "+set); System.out.println(((TreeSet<Integer>) set).comparator()); } }
Output
TreeSet = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] java.util.Collections$ReverseComparator@7ff95560
Time Complexity: O(n log n ) for inserting n elements (due to balanced tree operations).
Space Complexity: O(n) as TreeSet stores n elements.
Conclusion
Using a TreeSet with a custom comparator lets us change the default ordering behavior. With Collections.reverseOrder(), it is quite simple to order elements in reverse order rather than the default order. This technique comes in handy while dealing with ordered data where elements have to be ordered differently as per particular needs.