- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to create a TreeSet with custom Comparator
To create a TreeSet with custom comparator, let us first create a an Integer array and set it to TreeSet
Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
Above, we have used the Comparator with reverseOrder(), which returns a comparator that imposes the reverse of the natural ordering.
Example
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@6276ae34
Advertisements