To create a TreeSet
in Java that is sorted in descending order using a Comparator
, you can use the following steps:
Comparator
interface and override the compare
method to compare the elements in the desired order. For example, the following Comparator
implementation will sort the elements in descending order:public class DescendingComparator implements Comparator<Integer> { @Override public int compare(Integer a, Integer b) { return b - a; } }
TreeSet
object and pass in the comparator as an argument to the constructor:Set<Integer> set = new TreeSet<>(new DescendingComparator());
Here is an example of how you could use these steps to create a TreeSet
of integers that is sorted in descending order:
Set<Integer> set = new TreeSet<>(new DescendingComparator()); set.add(1); set.add(2); set.add(3); for (int i : set) { System.out.println(i); }
This will print out the numbers 3, 2, and 1, in that order.