ArrayList
Sort ArrayList example using Collections sort
In this example we shall show you how to sort an ArrayList using sort operation of the Collections API. To sort an ArrayList using Collections sort one should perform the following steps:
- Create a new ArrayList.
- Populate the arrayList with elements, using
add(E e)
API method of ArrayList. - Invoke
sort(List
API method of Collections to sort the arrayList elements in ascending order.list)
We can get the arrayList elements before and after sorting the list, to check the order of the elements. Before sorting the elements are in insertion order and after sorting they are in natural ascending order,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.ArrayList; import java.util.Collections; public class SortArrayList { public static void main(String[] args) { // Create an ArrayList and populate it with elements ArrayList arrayList = new ArrayList(); arrayList.add("element_1"); arrayList.add("element_3"); arrayList.add("element_5"); arrayList.add("element_2"); arrayList.add("element_4"); // ArrayList implementation maintains the insertion order for its elements System.out.println("Elements in ArrayList prior sorting :"); for(int i=0; i < arrayList.size(); i++) System.out.println(arrayList.get(i)); // Using Collection.sort static operation we can sort ArrayList elements in ascending order Collections.sort(arrayList); System.out.println("Elements in ArrayList after sorting :"); for(int i=0; i < arrayList.size(); i++) System.out.println(arrayList.get(i)); } }
Output:
Elements in ArrayList prior sorting :
element_1
element_3
element_5
element_2
element_4
Elements in ArrayList after sorting :
element_1
element_2
element_3
element_4
element_5
This was an example of how to sort an ArrayList using Collections sort in Java.