Monday, January 25, 2016

How to sort ArrayList in ascending/descending order in Java

Elements in ArrayList are displayed in the order of their inclusion in the list by defalut, but sometimes we need to iterate through the ArrayList to display elements in ascending or descending order. In this tutorial, we will implement a code that use Collections.sort () method that makes sorting a Arraylist in ascending and descending order.

Sort ArrayList in ascending order

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListAscendingOrder {

   public static void main(String[] args) {
      ArrayList unsorted = new ArrayList();
      unsorted.add("Ee");
      unsorted.add("5a");
      unsorted.add("c8");
      unsorted.add("41");
      unsorted.add("09");
  
      System.out.println("Before sort");
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i));
  
      System.out.println("\nAfter sort");
      Collections.sort(unsorted);
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i));
   }
}
Execution:

Avant le tri
Ee
5a
c8
41
09

Après le tri
09
41
5a
c8
Ee

Sort ArrayList in descending order

The Collections class has another method Collections.sort (List <T>, Comparator <T>). This method sort an ArrayList in both ascending and descending order. sort() method uses a comparator of objects that compare two objects using compareTo() method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListDescendingOrder{

   public static void main(String[] args) {
      ArrayList unsorted= new ArrayList();
      unsorted.add("000");
      unsorted.add("110");
      unsorted.add("101");
      unsorted.add("100");
      unsorted.add("111");
  
      System.out.println("Before sort");
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i)+" ");
  
      System.out.println("\nAfter sort");

      Collections.sort(unsorted, new Comparator() {
            @Override
            public int compare(String  s1, String  s2)
            {
                /*to get the descending order, we shall compare s2 with s1
                return s2.compareTo(s1);
            }
      });
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i)+" ");
   }
}
Execution:

Avant le tri
000
110
101
100
111

Après le tri
111
110
101
100
000

Rerefences:
stackOverFlow:How to sort a ArrayList in java
How to sort ArrayList in Java - BeginnersBook

No comments:

Post a Comment