1. Introduction

Sorting is a fundamental operation in programming and software development. The ArrayList class in Java provides a couple of convenient methods to sort its elements. In this post, we will demonstrate how to sort an ArrayList using the Collections.sort() method and the ArrayList.sort() method.

2. Program Steps

1. Initialize an ArrayList and populate it with some elements.

2. Sort the ArrayList using the Collections.sort() method and print the sorted ArrayList.

3. Shuffle the ArrayList elements to mix the order.

4. Sort the ArrayList using the ArrayList.sort() method and print the sorted ArrayList.

3. Code Program

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

public class ArrayListSorting {

    public static void main(String[] args) {

        // Step 1: Initialize an ArrayList and populate it with some elements
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Pineapple");
        fruits.add("Apple");
        fruits.add("Banana");

        // Step 2: Sort the ArrayList using Collections.sort() method and print the sorted ArrayList
        Collections.sort(fruits);
        System.out.println("Sorted ArrayList using Collections.sort() method: " + fruits);

        // Step 3: Shuffle the ArrayList elements to mix the order
        Collections.shuffle(fruits);
        System.out.println("ArrayList after shuffling: " + fruits);

        // Step 4: Sort the ArrayList using ArrayList.sort() method and print the sorted ArrayList
        fruits.sort(null);
        System.out.println("Sorted ArrayList using ArrayList.sort() method: " + fruits);
    }
}

Output:

Sorted ArrayList using Collections.sort() method: [Apple, Banana, Pineapple]
ArrayList after shuffling: [Banana, Pineapple, Apple]
Sorted ArrayList using ArrayList.sort() method: [Apple, Banana, Pineapple]

4. Step By Step Explanation

Step 1: We initialize an ArrayList named fruits and populate it with the strings "Pineapple", "Apple", and "Banana".

Step 2: We use the Collections.sort() method to sort the ArrayList in ascending order and then print the sorted ArrayList. The Collections.sort() method sorts the specified list into ascending order, according to the natural ordering of its elements.

Step 3: We shuffle the elements of the ArrayList using the Collections.shuffle() method to mix the order and demonstrate that the list can be re-sorted.

Step 4: We sort the ArrayList again, this time using the ArrayList.sort() method, and print the sorted ArrayList. The ArrayList.sort() method sorts the elements of the list according to their natural order or according to a specified Comparator. In this case, we pass null as we are using the natural ordering of the strings.