Skip to Content

Sort elements of Java ArrayList Example

  1. /*
  2.   Sort elements of Java ArrayList Example
  3.   This Java Example shows how to sort the elements of java ArrayList object using
  4.   Collections.sort method.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9.  
  10. public class SortJavaArrayListExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.    
  17.     //Add elements to Arraylist
  18.     arrayList.add("1");
  19.     arrayList.add("3");
  20.     arrayList.add("5");
  21.     arrayList.add("2");
  22.     arrayList.add("4");
  23.  
  24.     /*
  25.       To sort an ArrayList object, use Collection.sort method. This is a
  26.       static method. It sorts an ArrayList object's elements into ascending order.
  27.     */
  28.     Collections.sort(arrayList);
  29.    
  30.     //display elements of ArrayList
  31.     System.out.println("ArrayList elements after sorting in ascending order : ");
  32.     for(int i=0; i<arrayList.size(); i++)
  33.       System.out.println(arrayList.get(i));
  34.  
  35.   }
  36. }
  37.  
  38. /*
  39. Output would be
  40. ArrayList elements after sorting in ascending order :
  41. 1
  42. 2
  43. 3
  44. 4
  45. 5
  46. */