Monday, August 27, 2018

How to Sort Elements in Different Order in Java TreeSet

By default elements in TreeSet are sorted using natural ordering of the elements. If you want to sort a TreeSet in Java using different order than the natural order like in descending order or reverse order then you need to provide your own Comparator at Set creation time.

Let's see a Java example where TreeSet is sorted 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());
    
    citySet.add("Delhi");
    citySet.add("Mumbai");
    citySet.add("Bangalore");
    citySet.add("Chennai");
    citySet.add("Hyderabad");
    
    // Iterating the Set
    for(String str : citySet){
      System.out.println("City Name - " + str);
    }
  }
}

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

Output

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

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

That's all for this topic How to Sort Elements in Different Order in Java TreeSet. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Iterate a HashMap of ArrayLists of String in Java
  2. How to Sort ArrayList in Java
  3. How to sort arraylist of custom objects in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. Difference Between Comparable and Comparator in Java

You may also like-

  1. Convert String to double in Java
  2. Compressing And Decompressing File in GZIP Format
  3. How to Remove Duplicate Elements From an Array - Java Program
  4. LinkedHashSet in Java With Examples
  5. Synchronization in Java multithreading
  6. Difference between Checked exception & Unchecked exception
  7. Polymorphism in Java
  8. What is Dependency Injection in Spring

1 comment:

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

    http://www.javaproficiency.com/2015/11/how-to-sort-treeset-with-user-defined.html

    ReplyDelete