I am trying to sort a List of String arrays by its 3rd element. The 3rd element is a date value.
I've been trying to solve this for hours now by swapping but still can't get this solved.
For my current List, I don't believe Arrays.sort() would be ideal that's why I am sorting this via loop.
List<String[]> Record = new ArrayList<>();
Record.add(new String[] { "0001047166", "11047161", "20191223", "20200916" });
Record.add(new String[] { "0001047166", "11047162", "20191223", "20200916" });
Record.add(new String[] { "0001047166", "11047163", "20191222", "20200916" });
Record.add(new String[] { "0001047166", "11047166", "20191218", "20200916" });
Record.add(new String[] { "0001047359", "11047359", "20191217", "20200917" });
int size = Record.size();
int swapIndex = 0;
for (int i = 0; i < size-1; i++) {
String[] currentArray = Record.get(i); //get array on current index
String date = currentArray[2]; //get the date on 3rd position, index 2 of current array
swapIndex = i;
for (int j = i + 1; j < Record.size(); j++) {
String[] nextArray = Record.get(j); //get the next array (i + 1)
String otherDate = nextArray[2]; //get the date on 3rd position, index 2 of next arrray
if (date.compareTo(otherDate) > 0) {
String[] currArray = currentArray; //save the current array to temp
//swap
Record.set(swapIndex, nextArray);
Record.set(j, currArray);
swapIndex++;
}
}
}
//Display result
for (String[] a : Record) {
System.out.println(a[2]);
}
Output I get is
20191222 (wrong)
20191217
20191218
20191223
20191223
Desired output:
20191217
20191218
20191222
20191223
20191223
I'd appreciate any ideas or suggestions.
Thank you.
swapIndex++;?