Display a TreeSet in reverse order in Java

Java 8Object Oriented ProgrammingProgramming

To display a TreeSet in reverse order, you need to use Comparator. Let us first create an Integer array and use it for the TreeSet elements:

Integer arr[] = { 25, 100, 125, 200, 250, 400, 450, 550, 600, 700};

Now, use reverseOrde() comparator to reverse the natural ordering:

Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());

Now, add individual elements of the set as the Integer array elements:

for (int i = 0, l = arr.length; i < l; i++) {
   set.add(arr[i]);
}

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[] = { 25, 100, 125, 200, 250, 400, 450, 550, 600, 700};
      Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
      for (int i = 0, l = arr.length; i < l; i++) {
         set.add(arr[i]);
      }
      System.out.println("TreeSet (Reverse order) = "+set);
   }
}

Output

TreeSet (Reverse order) = [700, 600, 550, 450, 400, 250, 200, 125, 100, 25]
raja
Published on 24-Apr-2019 16:29:56
Advertisements