Skip to content

Java sort String array containing numbers example

Java sort string array containing numbers example shows how to sort string array containing numbers using a comparator in ascending and descending order.

How to sort string array containing numbers?

Java Arrays class provides the sort method which can be used to sort a string array.

This method sorts an array according to the natural ordering of the elements in the ascending order.

Let’s give it a try to see what happens when we try to sort a string array containing numbers.

Output

As you may have noticed from the output, the numbers are not sorted by their numeric values. This happens because sort method sorts string values based on the ASCII value of its characters. The ASCII value of zero is less than the ASCII value of 1, so “101” comes before the “11”.

In order to sort string values according to their numeric values, we need to write a custom Comparator as given below. The Comparator interface has the compare method which needs to be implemented by the implementing class.

The compare method should return 0 for the equal objects, a positive value if the object1 is greater than object2, and a negative value if the object1 is less than the object2 for sorting the objects in an ascending order.

Output

How to sort in descending order?

In the above example, we sorted an array of strings in the ascending order according to the numeric values of its elements. In order to sort an array in descending order, we need to change the custom comparator a bit.

The compare method should return 0 for the same objects, a negative value if object1 is greater than object2 and positive value if object1 is less than object2 if array needs to be sorted in descending order as given below.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.