How do I properly alphabetize (sort) a list of strings in a language-sensitive manner?

John Zukowski

This is actually outside the scope of the Collections Framework. Instead, it is part of the java.text package with the Collator and CollationKey classes.

The following example demonstrates this capability:

import java.text.*;
import java.util.*;

public class CollatorTest {
  public static void main(String args[]) {
    Collator collator = 
      Collator.getInstance();
    CollationKey key1 = 
      collator.getCollationKey("Tom");
    CollationKey key2 = 
      collator.getCollationKey("tom");
    CollationKey key3 = 
      collator.getCollationKey("thom");
    CollationKey key4 = 
      collator.getCollationKey("Thom");
    CollationKey key5 = 
      collator.getCollationKey("Thomas");

    Set set = new TreeSet();
    set.add(key1);
    set.add(key2);
    set.add(key3);
    set.add(key4);
    set.add(key5);
    printCollection(set);
  }
  static private void printCollection(
      Collection collection) {
    boolean first = true;
    Iterator iterator = collection.iterator();
    System.out.print("[");
    while (iterator.hasNext()) {
      if (first) {
        first = false;
      } else {
        System.out.print(", ");
      }      
      CollationKey key = 
        (CollationKey)iterator.next();
      System.out.print(key.getSourceString());
    }
    System.out.println("]");
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact