Sorting Array List in Java

This Java Tutorial section we demonstrates how to sort ArrayList in Java.

Sorting Array List in Java

This Java Tutorial section we demonstrates how to sort ArrayList in Java.

Sorting Array List in Java

Sorting Array List in Java

In this example you will learn about sorting array list in java using an example. By default array list are sorted as the element are inserted into the list. In Java ArrayList extends AbstractList implements List Interface. ArrayList are created with the initial size and exceed when the element increased. This example will explain sorting of ArrayList using Comparator, Comparable and Collectiolns.sort() method. ArrayList are dynamic in nature so they are also called dynamic array. But standard array are not dynamic in nature once the array is created they cannot be grow or shrink, fixed in size. ArrayList doesn't have sort() method. We can use the sort method of the Collections class. It sorts the Collection object. Now, here is the example to sort an ArrayList in java .

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class SortArrayList{
 
	public static void main(String args[]){
 
		List list = new ArrayList();
 
		list.add("D");
		list.add("G");
		list.add("A");
		list.add("XX");
		list.add("HHH");
		list.add("KK");
		list.add("abc");
		list.add("123");
		list.add("980");
 
		//before sort
		System.out.println("ArrayList before sort");
		for(String var: list){
			System.out.println(var);
		}
 
		//sort the list
		Collections.sort(list);
 
		//after sorted
		System.out.println("ArrayList after sort");
		for(String var: list){
			System.out.println(var);
		}
	}
 
}

Output from the program

Download Source Code