Descending order:

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListDesc {
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(1);
  15.             arrayList.add(2);
  16.             arrayList.add(3);
  17.            arrayList.add(4);
  18.             arrayList.add(5);
  19.             arrayList.add(6);
  20.  
  21.             /*
  22.            Use static Comparator reverseOrder() method of Collections 
  23.         utility class to get comparator object
  24.            */
  25.  
  26.          Comparator comparator = Collections.reverseOrder();
  27.  
  28.           System.out.println("Before sorting  : "  + arrayList);
  29.         
  30.  
  31.            /*
  32.               use
  33.               static void sort(List list, Comparator com) method of Collections class.
  34.             */
  35.  
  36.             Collections.sort(arrayList,comparator);
  37.             System.out.println("After sorting  : + arrayList);
  38.  
  39.        }
  40.     }
     

  1. OutPut:
  2. Before sorting  : [1, 2, 3, 4, 5, 6]
  3. After sorting  : [6, 5, 4, 3, 2, 1]
     

Ascending order:


  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListAsc{
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(10);
  15.             arrayList.add(4);
  16.             arrayList.add(7);
  17.            arrayList.add(2);
  18.             arrayList.add(5);
  19.             arrayList.add(3);
  20.  
  21.           
  22.  
  23.           System.out.println("Before sorting  : "  + arrayList);
  24.         
  25.  
  26.            /*
  27.               use
  28.               static void sort(List list) method of Collections class.
  29.             */
  30.  
  31.             Collections.sort(arrayList);
  32.             System.out.println("After sorting  : + arrayList);
  33.  
  34.        }
  35.     }
     



  1. OutPut:
  2. Before sorting  : [10, 4, 7, 2, 5, 3]
  3. After sorting  : [2, 3, 4, 5, 7, 10]

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu