Jump to Real's How-to Main page

Sort a String array

Sort utilities are now part of latest JDK versions.

Case sensitive

java.util.Arrays.sort(myArray);

Case insensitive

java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);

Sort with international characters.

Take the following example :

import java.util.*;
import java.io.*;

public class TestSort1 {

String [] words = { "Réal", "Real", "Raoul", "Rico" };

public static void main(String args[]) {
    new TestSort1().doit();
}

public void doit() {
    try {
      // to be able output french character at the console
      Writer w =
      new BufferedWriter
       (new OutputStreamWriter(System.out, "Cp850"));
      //
      w.write("Before :\n");
      for(int i=0; i < 4 ; i++) {
        w.write(words[i] + " ");
        }

      java.util.Arrays.sort(words);

      w.write("\nAfter :\n");
      for(int i=0; i < 4 ; i++) {
        w.write(words[i] + " ");
        }
      w.write("\n");
      w.flush();
      w.close();
      }
    catch(Exception e){}
    }
}
The output is :
Before :
Réal Real Raoul Rico
After :
Raoul Real Rico RéaAl
which is wrong since we expect to find "Réal" after "Real". To solve the problem , replace
java.util.arrays.sort(words);
by
java.util.arrays.sort(words, java.text.collator.getInstance(Locale.FRENCH));
and the output will be :
Before :
Réal Real Raoul Rico
After :
Raoul Real Réal Rico
Or you can do it the long way :
...
Locale loc = Locale.FRENCH;
sortArray(Collator.getInstance(loc), words);
...

public static void sortArray(Collator collator, String[] strArray) {
  String tmp;
  if (strArray.length == 1) return;
  for (int i = 0; i < strArray.length; i++) {
    for (int j = i + 1; j < strArray.length; j++) {
      if( collator.compare(strArray[i], strArray[j] ) > 0 ) {
        tmp = strArray[i];
        strArray[i] = strArray[j];
        strArray[j] = tmp;
        }
      }
    }
  }

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]