dantan04 dantan04 - 9 months ago 28
Android Question

Sort Java ArrayList with Letters before numbers

I am currently passing in an ArrayList to populate the titles of a TabLayout in Android. The elements in the array are strings:

["RCP", "RYL", "1", "2", "3", "4", "5", "6"].
Yet, not necessarily in that order.

I would like the list to be returned with the Letter elements first (alphabetically) and then integers rising, incrementally.

I have tried using the
Collections.sort
method, but this returns a list the rises numerically and then adds the "R" strings last:
["1", "2", "3", "4", "5", "6", "RCP", "RYL"]


To clarify, I would like to sort my ArrayList, so that it returns
["RCP", "RYL", "1", "2", "3", "4", "5", "6"]
It also needs to be flexible, as the titles of the "R", strings, are likely to change.

Thanks

Answer Source

If you want to give priority to strings that represents numbers over strings that do not, you should consider writing your own Comparator and pass it to the Collections.sort method.

This is a simple approach to your problem: check if any of the strings is a number, if so, give priority to the string that is not a number. If both are numbers or strings, use string's compareTo method.

Hope it helps.

public class Main {

    private static int customCompare(String a, String b) {
        return isThereAnyNumber(a, b)
                ? isNumber(a) ? 1 : -1
                : a.compareTo(b);
    }

    private static boolean isThereAnyNumber(String a, String b) {
        return isNumber(a) || isNumber(b);
    }

    private static boolean isNumber(String s) {
        return s.matches("[-+]?\\d*\\.?\\d+");
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("RCP", "RYL", "1", "2", "3", "4", "5", "6");
        Collections.sort(list, Main::customCompare);
        System.out.println(list);
    }
}

UPDATE

You can use an anonymous inner class that implements the Comparator interface in case you're not using Java 8.

public class Main {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("RCP", "RYL", "1", "2", "3", "4", "5", "6");
        Collections.sort(list, new Comparator<String>() {
            private boolean isThereAnyNumber(String a, String b) {
                return isNumber(a) || isNumber(b);
            }

            private boolean isNumber(String s) {
                return s.matches("[-+]?\\d*\\.?\\d+");
            }

            @Override
            public int compare(String a, String b) {
                return isThereAnyNumber(a, b)
                        ? isNumber(a) ? 1 : -1
                        : a.compareTo(b);
            }
        });
        System.out.println(list);
    }
}