Java Collection How to - Store string objects in treeset in descending order








Question

We would like to know how to store string objects in treeset in descending order.

Answer

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
/*from www  .ja  va  2  s . co m*/
public class Main {

  public static void main(String[] args) {
    TreeSetDesc sample = new TreeSetDesc();
    sample.addItemsToSet();
    sample.displaySet();
    sample.removeItems();
  }
}

class TreeSetDesc {

  private Set<String> set = null;
  private Comparator<String> comparator = null;

  public TreeSetDesc() {
    comparator = new SetComparator();
    set = new TreeSet<String>(comparator);
  }

  public void addItemsToSet() {
    String[] listItems = { "dog", "cat", "cow", "elephant", "sheep" };
    for (int i = 0; i < listItems.length; i++) {
      set.add(listItems[i]);
    }
  }

  public void displaySet() {
    System.out.println("Displaying contents of set");
    for (Object item : set) {
      System.out.println("Item = " + item.toString());
    }
  }

  public void removeItems() {
    System.out.println("Removing contents of set");
    set.remove("dog");
    set.remove("cat");
    set.remove("cow");
    set.remove("elephant");
    set.remove("sheep");
    System.out.println("Contents removed  ,now size of set = " + set.size());
  }
}
class SetComparator implements Comparator<String> {
  public int compare(String first, String second) {
    return second.compareTo(first);
  }
}

The code above generates the following result.