I have a list of "Report" objects with three fields (All String type)-
ReportKey StudentNumber School
I have a sort code goes like-
Collections.sort(reportList, new Comparator<Report>() { @Override public int compare(final Report record1, final Report record2) { return (record1.getReportKey() + record1.getStudentNumber() + record1.getSchool()) .compareTo(record2.getReportKey() + record2.getStudentNumber() + record2.getSchool()); } });
For some reason, I don't have the sorted order. One advised to put spaces in between fields, but why?
Do you see anything wrong with the code?
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.
The time complexity of Collections. sort() is O(n*log(n)) and a list sorted with Collections. sort() will only be sorted after the call to sort(). The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist).
To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
Do you see anything wrong with the code?
Yes. Why are you adding the three fields together before you compare them?
I would probably do something like this: (assuming the fields are in the order you wish to sort them in)
@Override public int compare(final Report record1, final Report record2) { int c; c = record1.getReportKey().compareTo(record2.getReportKey()); if (c == 0) c = record1.getStudentNumber().compareTo(record2.getStudentNumber()); if (c == 0) c = record1.getSchool().compareTo(record2.getSchool()); return c; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With