Sorting in Java

Our first program will demonstrate sorting in Java. Here’s the full source code:

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

public class Sorting {
    public static void main(String[] args) {
        // Sorting functions are available for many built-in types.
        // For a list of types that can be sorted, see the Comparable interface.

        // Sorting strings
        String[] strs = {"c", "a", "b"};
        Arrays.sort(strs);
        System.out.println("Strings: " + Arrays.toString(strs));

        // An example of sorting integers
        int[] ints = {7, 2, 4};
        Arrays.sort(ints);
        System.out.println("Ints:    " + Arrays.toString(ints));

        // We can also use the Collections class to check if
        // a list is already in sorted order.
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(2, 4, 7));
        boolean s = isSorted(list);
        System.out.println("Sorted:  " + s);
    }

    // Helper method to check if a list is sorted
    private static boolean isSorted(ArrayList<Integer> list) {
        return list.equals(new ArrayList<>(list.stream().sorted().toList()));
    }
}

To run the program, compile the code and then use java to execute it:

$ javac Sorting.java
$ java Sorting
Strings: [a, b, c]
Ints:    [2, 4, 7]
Sorted:  true

In this Java example, we use the Arrays.sort() method to sort arrays of primitive types and objects. For checking if a list is sorted, we create a helper method that compares the original list with a sorted version of itself.

Note that Java’s sorting methods are not generic in the same way as in some other languages, but they work for all types that implement the Comparable interface or can be compared using a Comparator.