samu joe samu joe - 5 months ago 31
Java Question

Java sorting alphabetical order of array

I am stuck on an issue. I am trying to sort via alphabetical order, I pasting my code snippet below and issue.

String[] arr = new String[3];

arr[0] = config.getfoldersdata() + "." + config.getCars();

arr[1] = config.getType();

arr[2] = entry.getVals() ? "Data" : "Entry";

// Arrays.sort(arr);
result.add(arr);


I want to sort alphabetically, the .getCars. The above code returns arr 1-3 in a single line/row. There can be multiple records/rows/line. So I want them to be sorted alphabetically, by what is returned by .getCars. The .getCars will return a string. I have tried the Arrays.sort above, but the re is no change in the result (no sorting). Where am I going wrong, am new to java. Thank you

Answer

Your design is awful: the arrays should in fact be objects.

But anyway, you just need a comparator which sorts the array based on their first element's natural ordering:

result.sort(Comparator.comparing(array -> array[0]));