Java Program to create a TreeSet with custom Comparator

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 24-Apr-2019 12:58:15
Advertisements