TreeMap’s addAll method to sort java Collection framework classes



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


Let’s see Example >

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);

Full program -
import java.util.Collection;
import java.util.HashSet;
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){
      Collection<Integer> collection = new HashSet<Integer>();
      collection.add(3);
      collection.add(1);
      collection.add(2);

      //TreeSet's addAll
      Set<Integer> treeSet = new TreeSet<Integer>();
      treeSet.addAll(collection);
      System.out.println("treeSet : "+treeSet);
     
  }
}
/*OUTPUT
treeSet : [1, 2, 3]
*/

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.
  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.




RELATED LINKS>

Program to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method



No comments:

Post a Comment