Sort an array of strings in Java

In this article, we will discuss various methods to sort an array of strings in Java.


 

1. Sort array of strings using Arrays.sort()

We can use Arrays class that has several static overloaded methods for sorting –

 

a. Arrays.sort(String[]) –

It sorts the specified array of strings into ascending order, according to the natural ordering of its elements. It uses Dual-Pivot Quicksort which is typically faster than traditional single-pivot Quicksort.

 

b. Arrays.sort(String[], Comparator) –

It sorts the specified array of strings according to the order induced by the specified comparator. It requires all elements of the array to be mutually comparable by the specified comparator. i.e. for any pair of strings (s1, s2) in the array, c.compare(s1, s2) should not throw a ClassCastException. This sort uses Iterative Merge Sort and produces a stable sort which means that the relative order of equal strings will be preserved.

 

To sort in Ascending order:

 

To sort in Descending order:

 
We can also write our custom comparator as shown below:

 

2. Sort array of strings using Arrays.parallelSort()

The Arrays.sort() method uses only single thread to sort the elements. Java 8 provides Arrays.parallelSort() which uses multiple threads for sorting and beats Arrays.sort() when number of elements cross a certain threshold. The prototype of parallelSort() is simlar to sort().

 

3. Sort array of strings using Java 8

We can also use Java 8 Stream API to sort an array of strings. The idea is to get sequential stream of strings from the specified string array and sort it according to natural order or in reverse order using a Comparator. Finally, we convert the sorted stream back to the string array.

 

To sort array of strings in ascending order:

 

To sort array of strings in descending order:

 

4. Sort array of strings using Collections.sort()

We know that Arrays.asList() method returns a fixed-size list backed by the specified array. That means any changes in the original array will be reflected in the returned list. We can make use of this fact to sort a list returned by Arrays.asList() using Collections.sort() method which in turn sorts the original array.

 
 
References: Arrays (Java Platform SE 8 )

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

avatar
  Subscribe  
Notify of