Sort Set by using TreeSet and by implementing Comparator and Comparable interface in java


In this Collection framework tutorial we will learn how to sort Set (using TreeSet and by implementing Comparator and Comparable interface) with lots of examples and programs in java.


Contents of page :
  • Example/Program 1 to Sort Set by using TreeSet(by default elements are sorted in ascending order), where elements are Integer type in java.
  • TreeMap’s addAll method or constructor for sorting>
  • Important Note :
  1. If any class that implements  Collection contains null.
  2. If any class that implements List is converted into TreeSet

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

  • Example/Program 3 to Sort Set in Ascending order by using TreeSet and implementing Comparable interface, where elements are customObject/Employee type in java.

  • Example/Program 4 to Sort Set in Ascending order by using TreeSet and implementing Comparator interface, where elements are customObject/Employee type in java.


Example/Program 1 to Sort Set by using TreeSet(by default elements are sorted in ascending order), where elements are Integer type in java.
TreeSet is sorted by natural order of elements (i.e. in ascending order) in java.
import java.util.TreeSet;
import java.util.Set;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortSetExample {
   public static void main(String...a){
       Set<Integer> treeSet = new TreeSet<Integer>();
       treeSet.add(3);
       treeSet.add(1);
       treeSet.add(2);
       System.out.println("treeSet : "+treeSet);
      
   }
}
/*OUTPUT
treeSet : [1, 2, 3]
*/



TreeMap’s addAll method or constructor for sorting in java>
If elements are stored in stored in HashSet/ArrayList or any other class that implements Collection  we can use TreeSet’s addAll method or constructor for sorting.

Let’s see Example in java >

Collection-
       Collection<Integer> collection = new HashSet<Integer>();
       collection.add(3);
       collection.add(1);
       collection.add(2);

TreeSet’s  addAll method -
       Set<Integer> treeSet = new TreeSet<Integer>();
       treeSet.addAll(collection);

TreeSet’s constructor -
       Set<Integer> treeSet = new TreeSet<Integer>(collection);


Important Note :
  1. If any class that implements  Collection contains null  - If any class that implements  Collection contains null  and is converted into TreeSet than NullPointerException (RunTimeException) will be thrown in java.
  2. If any class that implements List is converted into TreeSet -  Than that class’s duplicate elements will be lost, because any of the Set implementation ( TreeSet or may be any other class) does not allow to store duplicate elements in java.



Example/Program 2 to Sort Set by using TreeSet(we will define Comparator to sort elements in descending order), where elements are Integer type in java.
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 in java.
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortSetExample {
   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]
*/



Example/Program 3 to Sort Set in Ascending order by using TreeSet and implementing Comparable interface, where elements are customObject/Employee type in java.
TreeSet is sorted by natural order of elements in java.
In program 1 we used elements of Integer type, Integer class implements Comparable interface and overrides its compareTo() method.
But, for using Employee as elements we it must implement Comparable interface and override its compareTo() method.

Note : If we Employee don’t implement Comparable interface and override its compareTo() method than ClassCastException (RunTimeException) will be thrown. Because, internally TreeSet uses TreeMap for storing elements and TreeMap calls compare method for comparing elements, while comparing elements casting to java.lang.Comparable will fail at runtime.
import java.util.Set;
import java.util.TreeSet;
class Employee implements Comparable<Employee>{
   String name;
   String id;
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
   @Override
   public int compareTo(Employee otherEmployee) {
      //sort Employee on basis of name(ascending order)
      return this.name.compareTo(otherEmployee.name);
   }
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortSetExample {
   public static void main(String...a){
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");
       Set<Employee> treeSet = new TreeSet<Employee>();
       treeSet.add(emp1);
       treeSet.add(emp2);
       treeSet.add(emp3);
       System.out.println("treeSet : "+treeSet);
      
   }
}
/*OUTPUT

treeSet : [Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]

*/



Example/Program 4 to Sort Set in Ascending order by using TreeSet and implementing Comparator interface, where elements are customObject/Employee type in java.
In program 3, Employee implemented Comparable but in this program TreeSet will implement comparator interface.
Comparator interface has been used in form of anonymous inner class in java.

Note : If we Employee don’t implement Comparable interface neither Treeset implement Comparator interface than ClassCastException (RunTimeException) will be thrown. Because, internally TreeSet uses TreeMap for storing elements and TreeMap calls compare method for comparing elements, while comparing elements casting to java.lang.Comparable will fail at runtime.

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class Employee{
   String name;
   String id;
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortSetExample {
   public static void main(String...a){
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");
      Set<Employee> treeSet = new TreeSet<Employee>(new Comparator<Employee>() {
                 @Override
                 public int compare(Employee o1, Employee o2) {
                       return o1.name.compareTo(o2.name);
                 }
          });
       treeSet.add(emp1);
       treeSet.add(emp2);
       treeSet.add(emp3);
       System.out.println("treeSet : "+treeSet);
      
   }
}
/*OUTPUT
treeSet : [Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
*/


So in this Collection framework tutorial we learned how to sort Set (using TreeSet and by implementing Comparator and Comparable interface) with lots of examples and programs in java.




Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

Set hierarchy in java - Detailed - HashSet, CopyOnWriteArraySet, LinkedHashSet, TreeSet, ConcurrentSkipListSet, EnumSet classes


Comparable vs Comparator - differences and sorting list by implementing Comparable and Comparator in classes and inner classes in java


Arrays.sort to sort arrays by implementing Comparator and how Comparator of superclass can be used by subclasses in java


Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding its compare method and using TreeMap in java


Sort Map by value in Ascending and descending order by implementing Comparator interface and overriding its compare method in java




eEdit
Must read for you :