Java: sort a String array, whose strings represent int

Try a custom Comparator, like this:

    Arrays.sort(myarray, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    });

Hope you like it!


I think by far the easiest and most efficient way it to convert the Strings to ints:

int[] myIntArray = new int[myarray.length];

for (int i = 0; i < myarray.length; i++) {
    myIntArray[i] = Integer.parseInt(myarray[i]);
}

And then sort the integer array. If you really need to, you can always convert back afterwards:

for (int i = 0; i < myIntArray.length; i++) {
    myarray[i] = "" + myIntArray[i];
}

An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.


I found this article about sorting strings by numeric sorting also for strings that may or may not contain numbers:

The Alphanum Algorithm

There is a Java implementation example linked from the article. With that class you should be able to sort your arrays numerically like this:

Arrays.sort(myarray, new AlphanumComparator());

Tags:

Java

Sorting