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 list) API method of Collections to sort the arrayList elements in ascending order.
  • 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button