Skip to content

Java Sort String Array Example

Java String array sort example shows how to sort string array in Java using Collections class and custom comparator in descending and ascending orders.

How to sort String array in Java?

There are several methods using which you can sort an array of strings.

1) Sort string array using the Arrays class

A string array can be sorted using the sort method of the Arrays class.

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

Output

2) Using the Collections class

You can also use the sort method of Collections class along with the asList method to sort an array.

This method sorts the list in ascending order according to the natural order of its elements.

Note: The sort method of the Collections class accepts a List as an argument. To sort an array of strings, you first need to convert array to list using the asList method of the Arrays class.

Output

Please note that the asList method provides an abstract list view on the top of the original array. Hence, sorting a list will also modify the underlying original array.

How to sort array in descending order?

By default, the sort method of the Arrays and Collections class sorts an array in ascending order. However, you can use the reverseOrder method of the Collections class to sort array in descending order.

This method returns a comparator that uses the reverse of the natural ordering of the collection elements (descending order for string elements).

You can also use the sort method of the Collections class as given below.

Output

How to sort using custom comparator?

As you may have noticed from the output that when we sort an array using the sort method, it outputs “PlayStation” before “Playhouse” and “Zintec” before “ak56” string values.

That is because the sort method sorts string values according to the ASCII values. ASCII value of the capital letter “Z” (90) is less than the ASCII value of the small letter “a” (97) so “Zintec” comes before “ak56” value. What if you want to sort an array of string values regardless of the case of the values? A custom comparator can be used 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.