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
You may also like-
Nice post and must visit very simple example for sort treeset with user defined object
ReplyDeletehttp://www.javaproficiency.com/2015/11/how-to-sort-treeset-with-user-defined.html