In some situation is necessary make own custom sorting function. For this reason use class
java.util.Comparator. In this class instance you must override
compare() function.
/* -- array - one item with small first letter */
String[] array = { "one", "Two", "Three", "Four", "Fight" };
/* -- regular sorting */
Arrays.sort( array );
System.out.println( Arrays.toString( array ) );
/* -- sorting with own sorting function (ignoring letter size) */
Arrays.sort( array, new Comparator() {
@Override
public int compare( String s1, String s2 ) {
return( s1.compareToIgnoreCase( s2 ) );
}
});
System.out.println( Arrays.toString( array ) );
The output is:
[Fight, Four, Three, Two, one]
[Fight, Four, one, Three, Two]
First output row is regular sorting. Second row is our custom sorting function that ignores letter case size.
No comments:
Post a Comment