Program to Sort Set by using TreeSet(we will define Comparator to sort elements in descending order), where elements are Integer type.













TreeSet is sorted by natural order of elements (i.e. in ascending order), but we will implement Comparator interface and change the behaviour to sort elements in descending order.

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortSet {
   public static void main(String...a){
       Set<Integer> treeSet = new TreeSet<Integer>(new Comparator<Integer>() {
                 @Override
                 public int compare(Integer o1, Integer o2) {
                       //using Comparator to sort elements in descending order.
                       return o2.compareTo(o1);
                 }
          });
       treeSet.add(3);
       treeSet.add(1);
       treeSet.add(2);
       System.out.println("treeSet : "+treeSet);
      
   }
}
/*OUTPUT
treeSet : [3, 2, 1]
*/

No comments:

Post a Comment