Given a TreeSet in Java, task is to sort elements of TreeSet in Descending Order (descreasing order).
Examples:
Input : Set: [2, 3, 5, 7, 10, 20]
Output : Set: [20, 10, 7, 5, 3, 2]
Input : Set: [computer, for, geeks, hello]
Output : Set: [hello, geeks, for, computer]
Approach:
To make a TreeSet Element in decreasing order, simple use descendingSet() method which is used to change the order of TreeSet in reverse order
Below is the implementation of the above approach:
Java
import java.util.TreeSet;
public class TreeSetDescending
{
public static void main(String[] args)
{
TreeSet<Object> ints = new TreeSet<Object>();
ints.add( 2 );
ints.add( 20 );
ints.add( 10 );
ints.add( 5 );
ints.add( 7 );
ints.add( 3 );
TreeSet<Object> intsReverse =
(TreeSet<Object>)ints.descendingSet();
System.out.println( "Without descendingSet(): " +
ints);
System.out.println( "With descendingSet(): " +
intsReverse);
}
}
|
Output
Without descendingSet(): [2, 3, 5, 7, 10, 20]
With descendingSet(): [20, 10, 7, 5, 3, 2]
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
22 Oct, 2020
Like Article
Save Article