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"}
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.
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.
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.
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 String
s to int
s:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With