First, let's define an enumeration to the order we want to manage. This will hold the indexes that we want to uses for the sort.
private enum SortType {
FIRSTNAME(1, 0),
LASTNAME(0, 1);
int sortIndex;
int sortIndex2;
private SortType(int sortIndex, int sortIndex2){
this.sortIndex = sortIndex;
this.sortIndex2 = sortIndex2;
}
}
Note : This could be an array instead, allowing us to define an unlimited amount of "fallback" column.
Then, all we need to do is create the comparator to sort based on those two indexes :
private static void sort(String[][] array, SortType type){
Arrays.sort(array, (a1, a2) -> {
int r = a1[type.sortIndex].compareTo(a2[type.sortIndex]);
return r == 0 ? a1[type.sortIndex2].compareTo(a2[type.sortIndex2]) : r;
});
}
Let create the method to get the input from the user :
private static SortType getType(Scanner sc){
boolean again = false;
String input;
System.out.println("Sort option.\n1 : Firstname\n2: Lastname");
SortType type = null;
//Get a valid input for the type.
do{
input = sc.nextLine().trim();
if(input.equals("1")){
type = SortType.FIRSTNAME;
again = false;
} else if(input.equals("2")){
type = SortType.LASTNAME;
again = false;
} else {
System.out.println("Bad input, try again");
again = true;
}
}while(again);
return type;
}
And let's run it :
public static void main(String... args) {
String[][] array = { { "Bill", "Jones" }, { "Janet", "Kline" }, { "George", "Bailey" }, { "Ellan", "Sanches" }, { "Tom", "Nguyen" },
{ "William", "Walters" }, { "Author", "James" }, { "Henry", "Daniels" }, { "Mike", "Franklin" }, { "Julie", "Andrews" } };
System.out.println(Arrays.deepToString(array));
Scanner sc = new Scanner(System.in);
SortType type = getType(sc);
sc.close();
//Sort the array
sort(array, type);
//Print the array
System.out.println(Arrays.deepToString(array));
}
[[Bill, Jones], [Janet, Kline], [George, Bailey], [Ellan, Sanches], [Tom, Nguyen], [William, Walters], [Author, James], [Henry, Daniels], [Mike, Franklin], [Julie, Andrews]]
Sort option.
1 : Firstname
2: Lastname
sa
Bad input, try again
5
Bad input, try again
2
[[Author, James], [Bill, Jones], [Ellan, Sanches], [George, Bailey], [Henry, Daniels], [Janet, Kline], [Julie, Andrews], [Mike, Franklin], [Tom, Nguyen], [William, Walters]]