treeset java descending order using comparator

https‮w//:‬ww.lautturi.com
treeset java descending order using comparator

To create a TreeSet in Java that is sorted in descending order using a Comparator, you can use the following steps:

  1. Implement the 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;
    }
}
  1. Create a new TreeSet object and pass in the comparator as an argument to the constructor:
Set<Integer> set = new TreeSet<>(new DescendingComparator());
  1. Add elements to the set as desired. The set will be sorted in descending order according to the comparator.

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.

Created Time:2017-10-17 20:18:57  Author:lautturi