Java String Handling

Java Sort String Array Example

Java String Array Sort Example shows how to sort String array in Java. This example also shows how to sort String array using 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 Arrays class

String array can be sorted using sort method of Arrays class.

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

Output

2) Sort String array using Collections class

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

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

Note: sort method of Collections class accepts List as an argument. To sort an array of Strings, you first need to convert array to list using asList method of 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 String array in descending order in Java?

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

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

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

Output

How to sort String array using custom comparator?

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

That is because, sort method sorts String values according to the ASCII values. ASCII value of capital letter “Z” (90) is less than the ASCII value of 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

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.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *