- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Java Program to get maximum value with Comparator
- Java Program to get minimum value with Comparator
- Create a TreeSet in Java
- Java Program to create custom DateTime formatter
- Java Program to sort String Stream with reversed Comparator
- Java Program to merge duplicates of a List with TreeSet
- Java Program to get headset from TreeSet
- C++ Program to Create Custom Exception
- Java Program to get Sub Set from TreeSet
- Java Program to get Tail Set from TreeSet
- How to create a custom scrollbar with CSS?
- How to create a custom unchecked exception in Java?
- Can we create an enum with custom values in java?
- How to sort an array with customized Comparator in Java?
- Can we use Comparator with list in Java?

Advertisements