Sorting in Fortress

The Collections class in Java provides sorting functionality for built-in and user-defined types. Let’s look at sorting for built-in types first.

import java.util.ArrayList;
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 the Java documentation.

        List<String> strs = new ArrayList<>();
        strs.add("c");
        strs.add("a");
        strs.add("b");
        Collections.sort(strs);
        System.out.println("Strings: " + strs);

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

        // We can also use the Collections class to check if
        // a list is already in sorted order.
        boolean s = isSorted(ints);
        System.out.println("Sorted:  " + s);
    }

    // Java doesn't have a built-in method to check if a list is sorted,
    // so we'll implement a simple one.
    private static <T extends Comparable<? super T>> boolean isSorted(List<T> list) {
        if (list.size() <= 1) {
            return true;
        }
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i-1).compareTo(list.get(i)) > 0) {
                return false;
            }
        }
        return true;
    }
}

To run the program:

$ 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. Java’s sorting methods work with any class that implements the Comparable interface, which includes most built-in types like String and Integer.

We’ve also implemented a simple isSorted() method to check if a list is already sorted, as Java doesn’t provide this functionality out of the box. This method uses Java’s generics to work with any Comparable type.

Note that in Java, we use List<String> and List<Integer> instead of slices, as Java doesn’t have a direct equivalent to Go’s slices. The ArrayList class provides similar functionality.