How to sort an ArrayList in java

Let’s learn how to sort an ArrayList in java.

How to sort an ArrayList in java

To sort an ArrayList of String type we are using Collections.sort(arraylist) method.

import java.util.ArrayList;
import java.util.Collections;
public class SortArrayListOfStrings 
{
   public static void main(String[] args) 
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Banana");
      al.add("Pineapple");
      al.add("Jackfruit");
      al.add("Apple");
      al.add("Mango");
      // unsorted or given list
      System.out.println("ArrayList of Strings before sorting: ");
      for(String count : al)
      {
         System.out.println(count);
      }
      Collections.sort(al);
      // sorted list
      System.out.println("ArrayList of Strings after sorting: ");
      for(String str : al) 
      {
         System.out.println(str);
      }
   }
}


Output:

ArrayList of Strings before sorting:
Banana
Pineapple
Jackfruit
Apple
Mango
ArrayList of Strings after sorting:
Apple
Banana
Jackfruit
Mango
Pineapple


Similarly we can sort an ArrayList of Integers.

import java.util.ArrayList;
import java.util.Collections;
public class SortArrayListOfIntegers 
{
   public static void main(String[] args) 
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(86);
      al.add(22);
      al.add(61);
      al.add(83);
      al.add(59);
      al.add(39);
      // unsorted ArrayList
      System.out.println("ArrayList of Integers before sorting: ");
      for(int count: al)
      {
         System.out.println(count);
      }
      // sorted ArrayList
      Collections.sort(al);
      System.out.println("ArrayList of Integers after sorting: ");
      for(int num : al) 
      {
         System.out.println(num);
      }
   }
}


Output:

ArrayList of Integers before sorting:
86
22
61
83
59
39
ArrayList of Integers after sorting:
22
39
59
61
83
86


Also read – operators in java