Java array sorting: How to sort a Java String array

Java array FAQ: How do I sort a Java String array?

Java array-sorting solution

The solution is to use the Arrays.sort() method from java.util.Arrays. The short answer looks like this:

// create an example Java String array:
String[] fruits = {"banana", "orange", "kiwi", "apple"};

// sort the array, using the sort method of the Arrays class.
// `fruits` will be sorted after this is run:
Arrays.sort(fruits);

A complete example

The complete example looks like this:

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

Discussion

As mentioned, the only “trick” in this array sorting example is being aware of the Java 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.

Java String array - What’s Related

As I wrap up my collection of “Java String array” tutorials, here are a few links to my other String array tutorials: