How do I sort a collection or array of strings?
Author: Deron Eriksson
Description: This tutorial shows how to sort an array or collection of Strings.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


JavaSW makes sorting very easy. As an example of this, if you have an array of strings, you can sort the strings via a call to Arrays.sort(), such as:

Arrays.sort(stringArray);

If you require the Strings to be sorted without regards to case, you'll need a second argument, a Comparator, for Arrays.sort(). Such a comparator has already been written for us and can be accessed as a static on the String class named CASE_INSENSITIVE_ORDER.

Arrays.sort(stringArray, String.CASE_INSENSITIVE_ORDER);

Similarly if you have a collection of strings, you can sort the collection via calls to:

Collection.sort(stringCollection);

and

Collection.sort(stringCollection, String.CASE_INSENSITIVE_ORDER);

The StringSortExample class gives examples of sorting an array of strings and a list of strings. The array and collection are sorted with regards to case and then without regards to case.

StringSortExample.java

package example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class StringSortExample {

	public static void main(String[] args) throws Exception {

		String[] strArray = { "Carol", "bob", "Alice" };
		displayArray(strArray);

		Arrays.sort(strArray);
		displayArray(strArray);

		Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
		displayArray(strArray);

		System.out.println("---------------");

		List<String> strList = new ArrayList<String>();
		strList.add("larry");
		strList.add("Moe");
		strList.add("Curly");
		displayList(strList);

		Collections.sort(strList);
		displayList(strList);

		Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);
		displayList(strList);
	}

	public static void displayArray(String[] array) {
		for (String str : array) {
			System.out.print(str + " ");
		}
		System.out.println();
	}

	public static void displayList(List<String> list) {
		for (String str : list) {
			System.out.print(str + " ");
		}
		System.out.println();
	}

}

The console output is shown here. Notice after the first sort of the array and the first sort of the collection, the results have been alphabetized but case matters (uppercase words come before lowercase words). Notice that after the second sort of the array and the second sort of the collections, the results have been alphabetized without regards to case.

Console Output

Carol bob Alice 
Alice Carol bob 
Alice bob Carol 
---------------
larry Moe Curly 
Curly Moe larry 
Curly larry Moe 

If you require other types of sorting, you can write your own Comparator, where you define your sorting logic in the compare() method of the Comparator interface.