Sorting in Squirrel

Our example demonstrates sorting in Java using the Collections class for built-in types. We’ll look at sorting for built-ins first.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Sorting {
    public static void main(String[] args) {
        // Sorting functions in Java work for any Comparable type.
        // For a list of Comparable types, see Java's documentation.

        List<String> strs = Arrays.asList("c", "a", "b");
        Collections.sort(strs);
        System.out.println("Strings: " + strs);

        // An example of sorting integers.
        List<Integer> ints = Arrays.asList(7, 2, 4);
        Collections.sort(ints);
        System.out.println("Ints:    " + ints);

        // We can also use Java's Arrays class to check if
        // an array is already in sorted order.
        boolean s = Arrays.equals(ints.toArray(), ints.stream().sorted().toArray());
        System.out.println("Sorted:  " + s);
    }
}

To run the program, compile and execute it using the javac and java commands:

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

In this Java version, we use the Collections.sort() method to sort lists of strings and integers. The Collections.sort() method works with any list of Comparable objects, which includes most built-in Java types.

To check if a list is sorted, we convert it to an array and compare it with a sorted version of itself using Arrays.equals(). This approach is a bit more verbose than Go’s slices.IsSorted(), but it achieves the same result.

Note that in Java, we typically use List interfaces rather than raw arrays for more flexibility. The Arrays.asList() method is used to create a fixed-size list backed by an array, which is suitable for our sorting example.