Java String Handling

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. This example also shows how to sort an array in descending order.

How to sort String array containing numbers?

Java Arrays class provides sort method which can be used to sort 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 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. ASCII value of zero is less than ASCII value of 1, so “101” comes before “11”.

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

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

Output

How to sort String array containing numbers in descending order?

In above example, we sorted an array of Strings in 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.

compare method should return 0 for the same objects, 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

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.