Arrays Custom Sort
The following example shows how to sort any given array using Arrays.sort() API.
The sort functionality is embedded inside custom Comparator . This is
especially useful when we want to sort the same array different fashions.
package com.bethecoder.tutorials.utils.arrays;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysCustomSort {
public static void main ( String [] args ) {
Rank [] rankList = new Rank [] {
new Rank ( 6 ) , new Rank ( 2 ) , new Rank ( 4 ) , new Rank ( 1 ) ,
new Rank ( 5 ) , new Rank ( 3 ) , new Rank ( 9 ) , new Rank ( 8 )
} ;
System.out.println ( "Before sort : " + Arrays.toString ( rankList )) ;
Arrays.sort ( rankList, new Comparator<Rank> () {
@Override
public int compare ( Rank first, Rank second ) {
if ( second.getRank () < first.getRank ()) {
return 1 ;
} else if ( first.getRank () < second.getRank ()) {
return - 1 ;
}
return 0 ;
}
}) ;
System.out.println ( "After sort : " + Arrays.toString ( rankList )) ;
}
}
class Rank {
int rank;
public Rank ( int rank ) {
super () ;
this .rank = rank;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this .rank = rank;
}
public String toString () {
return "Rank[" + rank + "]" ;
}
}
It gives the following output,
Before sort : [Rank[6], Rank[2], Rank[4], Rank[1], Rank[5], Rank[3], Rank[9], Rank[8]]
After sort : [Rank[1], Rank[2], Rank[3], Rank[4], Rank[5], Rank[6], Rank[8], Rank[9]]