Java Sort an array of Strings - Arrays.sort() method

In this source code example, we will see how to sort an array of Strings using Arrays.sort() method with an example.

Sorting an array of Strings - Arrays.sort() method

package com.java.array.tutorial.sorting;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Sorting an array of Strings - Arrays.sort() method
 * @author Ramesh Fadatare
 *
 */
public class SortingArrayExamples {
    public static void main(String[] args) {
        // Sorting an array of Strings - Arrays.sort() method
        String[] strArray = {
            "B",
            "D",
            "A",
            "C",
            "E"
        };

        // ascending order
        System.out.println("Before sorting => " + Arrays.toString(strArray));
        Arrays.sort(strArray);
        System.out.println("After sorting => " + Arrays.toString(strArray));

        // descending order
        System.out.println("Before sorting => " + Arrays.toString(strArray));
        Arrays.sort(strArray, Comparator.reverseOrder());
        System.out.println("After sorting => " + Arrays.toString(strArray));
    }
}
Output:
Before sorting => [B, D, A, C, E]
After sorting => [A, B, C, D, E]
Before sorting => [A, B, C, D, E]
After sorting => [E, D, C, B, A]

Reference


Comments