Object Sorting Example in Collection Framework

TreeSet provides an implementation of the Set interface that uses a tree for storage and guarantees that the elements will be in ascending order, according to natural orde. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
1. Sort An Array Example

import java.util.Arrays; public class SortArray { public static void main(String s[]) { String[] name = new String[] {"Sunil","Anand", "Aman", "Sanjeev"}; Arrays.sort(name); int i=1; for(String str: name){ System.out.println("Name " + i + " : " + str); i++; } } }
Output

Name 1 : Aman
Name 2 : Anand
Name 3 : Sanjeev
Name 4 : Sunil

Download this example
2. Sort A List Example

import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Collections; public class ListSorting { public static void main(String s[]) { List list=new ArrayList(); list.add("Sunil"); list.add("Anand"); list.add("Aman"); list.add("Sanjeev"); Collections.sort(list); Iterator it=list.iterator(); int i=1; while(it.hasNext()) { System.out.println("Name " + i + " : " + it.next()); i++; } } }
Output

Name 1 : Aman
Name 2 : Anand
Name 3 : Sanjeev
Name 4 : Sunil

Download this example
 



 

Latest Tutorial


Most Visited Tutorial