Java Collection How to - Create a TreeSet(Sorted Set) with custom Comparator








Question

We would like to know how to create a TreeSet(Sorted Set) with custom Comparator.

Answer

//from  www .  j  ava  2 s .  c  o  m
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

public class MainClass {
  public static void main(String args[]) throws Exception {
    String elements[] = { "A", "C", "D", "G", "F" };
    Set set = new TreeSet(Collections.reverseOrder());
    for (int i = 0, n = elements.length; i < n; i++) {
      set.add(elements[i]);
    }
    System.out.println(set);
    System.out.println(((TreeSet) set).comparator());
  }
}

The code above generates the following result.