Friday, 23 October 2015

How to Sort elements in different order in TreeSet - Java Program

By default elements are stored in TreeSet using natural ordering. If you want to sort using different order then you need to provide your own comparator at set creation time. Let's see an example where we sort the Strings in descending order rather than the natural ordering (which is ascending in case of String).

  public class TreeSetDemo {
    public static void main(String[] args) {
        // Providing custom compartor
        Set<String> citySet = new TreeSet<String>(new CityComparator());
        // Iterating the Set
        for(String str : citySet){
            System.out.println("City Name - " + str);

// Comparator class
class CityComparator implements Comparator<String>{
    public int compare(String str1, String str2) {
        return str2.compareTo(str1);


City Name - Mumbai
City Name - Hyderabad
City Name - Delhi
City Name - Chennai
City Name - Bangalore

Here note that a comparator is provided which reverses the sorting order. That comparator is provided at the set creation time in a constructor.

That's all for this topic How to sort elements in different order in TreeSet. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. Difference between Comparable and Comparator
  2. LinkedHashSet in Java
  3. How to sort arraylist in Java
  4. How to sort arraylist of custom objects in Java
  5. Count total number of times each character appears in a String

You may also like -

>>>Go to Java Programs page

1 comment:

  1. Nice post and must visit very simple example for sort treeset with user defined object