Friday, September 10, 2021

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());
    // 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 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. Compress And Decompress File Using GZIP Format in Java
  3. Remove Duplicate Elements From an Array in Java
  4. LinkedHashSet in Java With Examples
  5. Synchronization in Java - Synchronized Method And Block
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Polymorphism in Java
  8. Dependency Injection in Spring Framework

1 comment:

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