Skip to content

Instantly share code, notes, and snippets.

@mitchwongho
Created December 12, 2013 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchwongho/7925127 to your computer and use it in GitHub Desktop.
Save mitchwongho/7925127 to your computer and use it in GitHub Desktop.
Java implementation of a Comparator that sorts a list of Objects (using Object.toString() ) alphanumerically (case-insensitive)
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Sorts list of {@code Object} entries alphanumerically.
*/
public class AlphaNumericSorter {
/**
* Compare using the Object's toString() value
*/
private static Comparator<Object> comp = new Comparator<Object>() {
private NumberFormat nf = NumberFormat.getNumberInstance();
@Override
public int compare( Object lhs, Object rhs ) {
// sort alphabetically...uncategorised always at the bottom
String lhsTitle = lhs.toString();
String rhsTitle = rhs.toString();
if ( lhsTitle.equalsIgnoreCase( rhsTitle ) ) {
// LHS == RHS
return 0;
} else {
int retval = 0;
final String[] lha = lhsTitle.split( "\\s+" ); // split into
// words
final String[] rha = rhsTitle.split( "\\s+" ); // split into
// words
for ( int i = 0; i < Math.max( lha.length, rha.length ); i++ ) {
if ( lha[i].equalsIgnoreCase( rha[i] ) ) {
retval = 0;
} else {
if ( isNumberic( lha[i] ) && isNumberic( rha[i] ) ) {
try {
final double lhd = nf.parse( lha[i] )
.doubleValue();
final double rhd = nf.parse( rha[i] )
.doubleValue();
if ( lhd > rhd ) {
retval = 1;
break;
} else {
retval = -1;
break;
}
} catch ( ParseException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
retval = lha[i].compareToIgnoreCase( rha[i] );
if ( retval != 0 )
break;
}
}
//
if ( lha.length == rha.length )
continue;
if ( i + 1 == lha.length && lha.length < rha.length ) {
retval = -1;
} else if ( i + 1 == rha.length
&& lha.length > rha.length ) {
retval = 1;
}
}
return retval;
}
}
/**
* Test {@code str} as a number
* @param str the String to test
* @return true if {@code str} is a number
*/
private boolean isNumberic( final String str ) {
boolean isNumberic = false;
try {
nf.parse( str );
isNumberic = true;
} catch ( Exception e ) {
}
return isNumberic;
}
};
/**
* Perform the sorting
* @param unsorted the unsorted list
* @param uncategorisedTitle the String used for uncategorised item category
*/
public static void sort( final List<Object> unsorted,
final String uncategorisedTitle ) {
Collections.sort( unsorted, comp );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment