Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing Sort Order

Status
Not open for further replies.

JoeOCLC

Programmer
Aug 29, 2003
8
US
We are displaying a list of objects in a JSP window and sorting it using the stardard Arrays.sort with a specialized comparator to sort on just one string within the object. Our product managers aren't happy with the standard lexicographic sorting that java uses. They want the special characters (~, !, @, etc) to appear at the head of the list instead of the tail.

Are there any suggestions on easy ways to write the comparator for this?

--

Joe Nelson
OCLC Online Computer Library Center, Inc.
Dublin, OH
 
This code should do it:

Code:
String[] list = { "asadfdsf", "@aaadfdsf", "!safdsf" };
Arrays.sort(list, 
            new Comparator() {
              public int compare(Object arg0, Object arg1) {
                  return ((String)arg0).compareTo(arg1);
              }
            }
           );
 
This only partially works. Try putting an underscore "_" or a tilde "~" at the start of the string.

It sorts by ASCII code, and there are special characters "out of order" in ASCII.

--

Joe Nelson
OCLC Online Computer Library Center, Inc.
Dublin, OH
 
ok. you will have to spec out all those special characters. Assuming you only interested in ASCII characters, then you can have a function to replace to special characters in the string before compare them. example:

Code:
public String replaceSpecialChar(String s) {
  StringBuffer sb = new StringBuffer();
  for (int i=0; i<s.length(); i++) {
    char charVar = s.charAt(i);
    switch (charVar) {
      case '[': charVar = (char)0; break; 
      case '\\': charVar = (char)1; break; 
      case ']': charVar = (char)2; break; 
      case '^': charVar = (char)3; break; 
      case '_': charVar = (char)4; break; 
      case (char)140: charVar = (char)5; break;
      case '{': charVar = (char)6; break;
      case '|': charVar = (char)7; break;
      case '}': charVar = (char)8; break;
      case '~': charVar = (char)9; break;
    }
    sb.append(charVar);
  }
  return sb.toString();
}

String[] list = { "asadfdsf", "@aaadfdsf", 
                  "!safdsf", "[sdfdsaf", 
                  "bbbb", "_asfdfadsf"};
Arrays.sort(list, new Comparator() {
  public int compare(Object arg0, Object arg1) {
    String a = replaceSpecialChar((String)arg0);
    String b = replaceSpecialChar((String)arg1);
    return (a.compareTo(b));
  }
});
 
Right, I've found an easier way by simply checking to see if its a digit, char or otherwise.

Thanks anyway...

--

Joe Nelson
OCLC Online Computer Library Center, Inc.
Dublin, OH
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top