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 :
- 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.
RELATED LINKS>
Program to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method
Labels:
Collection programs
Core Java