how-to

Arrays

How to make custom array sorting

For sorting array elements use class java.util.Arrays. That class contains static methods for work with arrays.

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 items 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 shows regular sorting. Second row is our custom sorting function that ignores letter case size.