Search code examples
javacompareto

Will the variables order in compareTo make difference?


Given a list of non negative integers, I would like to arrange them such that they form the largest number. Given [1, 20, 23, 4, 8], the largest formed number is 8423201. But I want to figure how the order of the variables in compareTo method influences the result of Arrays.sort. e.g, what's the difference between (s2 + s1).compareTo(s1 + s2) and (s1 + s2).compareTo(s2 + s1).

enter code here

private static class NumbersComparator implements Comparator<String> {
        @Override
        public int compare(String s1, String s2){
            return (s2 + s1).compareTo(s1 + s2);
        }
    }
String strs = {"1", "20", "23", "4", "8"};
Arrays.sort(strs, new NumbersComparator());

Solution

  • Sort the numbers with reverse (descending) lexicographical order, that is the numbers are sorted with String(s) in the default reverse order. Like,

    String[] strs = { "1", "20", "23", "4", "8" };
    Stream.of(strs).sorted(Comparator.reverseOrder()) // <-- sort in reverse order
        .forEachOrdered(System.out::print);
    System.out.println();
    

    Which outputs

    8423201
    

    Because 8 is greater than the first digit of all the other numbers, 4 is the next, and so on.