Sorting in Karel

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

public class Sorting {
    public static void main(String[] args) {
        // Sorting functions in Java work for arrays and collections
        // of Comparable objects.

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

        // An example of sorting integers
        Integer[] 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.
        List<Integer> intList = Arrays.asList(ints);
        boolean s = isSorted(intList);
        System.out.println("Sorted:  " + s);
    }

    // Helper method to check if a list is sorted
    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;
    }
}

In Java, we use the Arrays.sort() method to sort arrays of primitive types or objects. For collections, we can use Collections.sort(). Unlike Go, Java doesn’t have a built-in slices package, so we need to use different approaches for arrays and collections.

The Arrays.sort() method is used to sort the arrays of strings and integers. For checking if a list is sorted, we’ve implemented a custom isSorted() method, as Java doesn’t provide a direct equivalent to Go’s slices.IsSorted().

To run this program:

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

This example demonstrates how to sort arrays of different types and check if a list is sorted in Java. The Arrays and Collections classes provide various utility methods for working with arrays and collections, including sorting.