Java array FAQ: Can you share an example of how to sort a Java String array?
In an earlier tutorial, I demonstrated how to create Java String arrays, and in this tutorial I'll continue along that line and demonstrate how to sort a Java String array.
The following Java class demonstrates how to create and sort a String array. In short, you can easily sort an array with the Arrays class sort method, shown in bold below:
import java.util.Arrays;
public class JavaSortStringArray
{
public static void main(String[] args)
{
// create a Java String array
String[] fruits = {"banana", "orange", "kiwi", "apple"};
// sort the array, using the sort method of the Arrays class
Arrays.sort(fruits);
// print the sorted results
for (String fruit : fruits)
{
System.out.println(fruit);
}
}
}
As you might imagine, the output from this array sorting example looks like this:
apple banana kiwi orange
As mentioned, the only "trick" in this array sorting example is being aware of the Arrays class, and the sort method of that class.
I decided to write this tutorial after seeing someone write their own String array sorting algorithm. I know it's hard sometimes to be aware of the complete Java API, so I hope that by sharing this array sorting example, this solution will be easier to find.
If you have any questions or comments, just leave them in the comments section below and I'll get back with you.
As I wrap up my collection of "Java String array" tutorials, here are a few links to my other String array tutorials:
Post new comment