Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a String array, whose strings represent int

Tags:

java

sorting

I have String[] array like

{"3","2","4","10","11","6","5","8","9","7"}

I want to sort it in numerical order, not in alphabetical order.

If I use

Arrays.sort(myarray);

I obtain

{"10","11","2","3","4","5","6","7","8","9"}

instead of

{"2","3","4","5","6","7","8","9","10","11"}
like image 217
Sefran2 Avatar asked Mar 08 '13 08:03

Sefran2


People also ask

How do you sort an integer string array?

Convert each element in the String array obtained in the previous step into an integer and store in into the integer array. The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.

Can we sort string and integer in Java?

String in Java is immutable. There is no direct method to sort a string in Java. You can use Arrays, which has a method CharArray() that will create a char input string and using another method (Arrays.

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.


2 Answers

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!

like image 88
vikingsteve Avatar answered Oct 18 '22 03:10

vikingsteve


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.

like image 39
devrobf Avatar answered Oct 18 '22 03:10

devrobf