Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 238
dantan04 Avatar asked Mar 11 '17 19:03

dantan04


1 Answers

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);
    }
}
like image 135
acontell Avatar answered Oct 04 '22 19:10

acontell