Saturday, 31 October 2015

How to sort an ArrayList on Increasing and Decreasing Order

In this Java tutorial, I will teach you how to sort an ArrayList on both increasing and decreasing order of elements. Though, we will use ArrayList of Integers on examples, you can practically sort any list by using this technique. Only requirement is that your object should implement Comparable interface otherwise you need to pass Comparator implementation to sort objects stored inside list. The sort() method is defined inside java.util.Collections class. It is overloaded to accept a Comparator. The version which doesn't take any argument sort the given list on default order e.g. increasing order for integers. This is defined by their compareTo() method which comes from Comparable interface. The version which takes Comparator, uses that to sort the list, as we have done to sort the list in reverse or decreasing order.


How to sort ArrayList on Increasing and Decreasing order

Below is the sample code for doing this sorting. You can practically sort any type of ArrayList using this technique.

package beginner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Simple Java program to demonstrate how to sort an ArrayList on
 * increasing and decreasing order of elements.
 *
 * @author Soma
 *
 */
public class ArrayListApp{

    public static void main(String... args){
    
     // sample ArrayLsit of integers, contains duplicates as well
     List<Integer> listOfNumbers = new ArrayList<>(
                         Arrays.asList(2, 4, 2, 1, 4, 5, 3, 6, 7, 9));
    
    
     System.out.println("list before sorting: " + listOfNumbers);
    
     // Sorting ArrayList on increasing order
     Collections.sort(listOfNumbers);
    
     System.out.println("list before sorting on increasing order: "  
                               + listOfNumbers);
    
     // Sorting ArrayList on decreasing order
     Collections.sort(listOfNumbers, Collections.reverseOrder());
    
     System.out.println("list after sorting on decreasing  order: " 
                               + listOfNumbers);

    }

}

Output

list before sorting: [2, 4, 2, 1, 4, 5, 3, 6, 7, 9]
list before sorting on increasing order: [1, 2, 2, 3, 4, 4, 5, 6, 7, 9]
list after sorting on decreasing  order: [9, 7, 6, 5, 4, 4, 3, 2, 2, 1]
 
Thank you for reading my tutorials.  If you have any doubt then please let me know, I would be happy to help you.



No comments:

Post a Comment